我试着比较这三个,但似乎只有array_map
有效。
$input = array( ' hello ','whsdf ',' lve you',' ');
$input2 = array( ' hello ','whsdf ',' lve you',' ');
$input3 = array( ' hello ','whsdf ',' lve you',' ');
$time_start = microtime(true);
$input = array_map('trim',$input);
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did array_map in $time seconds<br>";
foreach($input as $in){
echo "'$in': ".strlen($in)."<br>";
}
////////////////////////////////////////////////
$time_start = microtime(true);
array_walk($input2,'trim');
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did array_walk in $time seconds<br>";
foreach($input2 as $in){
echo "'$in': ".strlen($in)."<br>";
}
////////////////////////////////////////////////
$time_start = microtime(true);
foreach($input3 as $in){
$in = trim($in);
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did foreach in $time seconds<br>";
foreach($input3 as $in){
echo "'$in': ".strlen($in)."<br>";
}
我做错了什么?下面是输出:
Did array_map in 0.00018000602722168 seconds
'hello': 5
'whsdf': 5
'lve you': 7
'': 0
Did array_walk in 0.00014209747314453 seconds
' hello ': 10
'whsdf ': 41
' lve you': 37
' ': 30
Did foreach in 0.00012993812561035 seconds
' hello ': 10
'whsdf ': 41
' lve you': 37
' ': 30
它不会对array_walk
和foreach
循环进行裁剪。
发布于 2012-05-05 03:54:19
array_walk
不会查看结果函数提供了什么。相反,它向回调传递对项值的引用。因此,要使其正常工作,代码需要
function walk_trim(&$value) {
$value = trim($value);
}
foreach
本身也不存储更改的值。将其更改为
foreach ($input3 as &$in) {
$in = trim($in);
}
发布于 2013-06-05 13:39:25
从PHP5.3开始,匿名函数成为可能。例如:
$arr = array('1<br/>','<a href="#">2</a>','<p>3</p>','<span>4</span>','<div>5</div>');
array_walk($arr, function(&$arg){
$arg = strip_tags($arg);
});
var_dump($arr); // 1,2,3,4,5 ;-)
玩得开心。
https://stackoverflow.com/questions/10458660
复制