26

これら3つを比較しようとしていますが、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_walkforeach

4

2 に答える 2

20

array_walk結果関数が与えるものを見ていません。代わりに、項目値への参照をコールバックに渡します。したがって、それが機能するためのコードは

function walk_trim(&$value) {
    $value = trim($value);
}

foreach変更された値自体も保存しません。に変更します

foreach ($input3 as &$in) {
    $in = trim($in);
}

参考文献についてもっと読む

于 2012-05-05T03:54:19.483 に答える