如果你使用PHP 5.3+,然後匿名函數可以使你的代碼會更加清晰,但一個簡單的for循環有最棒的表演。 (使用array_walk
接近雖然!)
我跑了一些測試用幾種不同的方法(使用PHP 33年4月5日):
function makeArray(&$a) {
$a = array();
for($i = 0; $i < 100000; $i++) {
$a[rand()] = rand();
}
return $a;
}
makeArray($array);
$before = microtime(true);
$result = implode(
",",
array_map(
function($k, $v) {
return "$k:$v";
},
array_keys($array),
$array
)
);
$after = microtime(true);
$dur = $after - $before;
echo "Array Map w/ anonymous function: {$dur}s<br>";
makeArray($array);
$before = microtime(true);
function kv_func($k, $v) {
return "$k:$v";
}
$result = implode(
",",
array_map(
"kv_func",
array_keys($array),
$array
)
);
$after = microtime(true);
$dur = $after - $before;
echo "Array Map w/ function: {$dur}s<br>";
makeArray($array);
$before = microtime(true);
array_walk(
$array,
function(&$v, $k) {
$v = "$k:$v";
}
);
$result = implode(
",",
$array
);
$after = microtime(true);
$dur = $after - $before;
echo "Array Walk w/ anonymous function: {$dur}s<br>";
makeArray($array);
$before = microtime(true);
$ff = true;
$sep = ",";
$out = "";
foreach($array as $key => $val) {
if($ff) $ff = false;
else $out .= $sep;
$out .= "$key:$val";
}
$after = microtime(true);
$dur = $after - $before;
echo "Foreach loop w/ loop flag: {$dur}s<br>";
makeArray($array);
$before = microtime(true);
$out = "";
foreach($array as $key => $val) {
$out .= "$key:$val,";
}
$out = substr($out, 0, -1);
$after = microtime(true);
$dur = $after - $before;
echo "Foreach loop + substr: {$dur}s<br>";
結果:
Array Map w/ anonymous function: 0.13117909431458s
Array Map w/ function: 0.13743591308594s // slower than anonymous
Array Walk w/ anonymous function: 0.065797805786133s // close second
Foreach loop w/ loop flag: 0.042901992797852s // fastest
Foreach loop + substr: 0.043946027755737s // comparable to the above
而只是踢,我嘗試了for循環而不糾正尾隨逗號。它並沒有真正的影響:
Foreach loop w/ trailing comma: 0.044748067855835s
嘗試[序列化](http://php.net/manual/en/function.serialize.php)或[json encoding](http:// php。 net/manual/en/function.json-encode.php)數組。 – undefined