Answers:
array_map('rtrim', $fruit);
。希望对您
array_walk()
可用于trim()
修剪数组
<?php
function trim_value(&$value)
{
$value = trim($value);
}
$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);
array_walk($fruit, 'trim_value');
var_dump($fruit);
?>
如果数组是多维数组,则将非常有用:
//trims empty spaces in array elements (recursively trim multidimesional arrays)
function trimData($data){
if($data == null)
return null;
if(is_array($data)){
return array_map('trimData', $data);
}else return trim($data);
}
一个样本测试是这样的:
$arr=[" aaa ", " b ", "m ", [" .e ", " 12 3", "9 0 0 0 "]];
print_r(trimData($arr));
//RESULT
//Array ( [0] => aaa [1] => b [2] => m [3] => Array ( [0] => .e [1] => 12 3 [2] => 9 0 0 0 ) )
如果要修剪和打印一维数组或多维数组的最深维度,则应使用:
foreach($array as $key => $value)
{
$array[$key] = trim($value);
print("-");
print($array[$key]);
print("-");
print("<br>");
}
如果要修剪但不想打印一维数组或多维数组的最深维度,则应使用:
$array = array_map('trim', $array);
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function generateRandomSpaces() {
$output = '';
$i = rand(1, 10);
for ($j = 0; $j <= $i; $j++) {
$output .= " ";
}
return $output;
}
// Generating an array to test
$array = [];
for ($i = 0; $i <= 1000; $i++) {
$array[] = generateRandomSpaces() . generateRandomString(10) . generateRandomSpaces();
}
// ARRAY MAP
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
$trimmed_array=array_map('trim',$array);
}
$time = (microtime(true) - $start);
echo "Array map: " . $time . " seconds\n";
// ARRAY WALK
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
array_walk($array, 'trim');
}
$time = (microtime(true) - $start);
echo "Array walk : " . $time . " seconds\n";
// FOREACH
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
foreach ($array as $index => $elem) {
$array[$index] = trim($elem);
}
}
$time = (microtime(true) - $start);
echo "Foreach: " . $time . " seconds\n";
// FOR
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
for ($j = 0; $j < count($array) - 1; $j++) {
$array[$j] = trim($array[$j]);
}
}
$time = (microtime(true) - $start);
echo "For: " . $time . " seconds\n";
上面的代码输出为:
数组映射:8.6775720119476秒
数组游走:10.423238992691秒
Foreach:7.3502039909363秒
:7.3502039909363秒:9.8266389369965秒
当然,这个值可能会改变,但是我想说foreach是最好的选择。
如果您的值为NULL,则在array_map更改类型中进行修剪。
更好的方法:
$result = array_map(function($v){
return is_string($v)?trim($v):$v;
}, $array);
只需使用正则表达式来修剪所有空间或最小化数组项
$array = array_map(function ($item) {
return preg_replace('/\s+/', '', $item);
}, $array);