如何在 PHP 中遍历关联数组并访问键和数据


How to traverse associative array in PHP and access both key and data

我想在PHP中遍历一个关联数组,并以最有效的方式访问密钥和数据。这必须是重复的,但我在SO的任何地方都找不到"最佳实践"示例,上面写着"这是在PHP中做到这一点的最终方法"。

例:

$array = ["one"=>"un", "two"=>"deux", "three"=>"trois"];
foreach ($array as $value){
    $key = array_search($value, $array);
    print_r($key);
    print_r($value);
}

这太可怕了;当它搜索键时,它每次迭代遍历一次。有没有更好的方法来访问数组的索引?

编辑:在我的机器上进行 100k 迭代需要 5.28 秒。 php -a

$start=microtime(true);for ($i = 0; $i < 100000; $i++){foreach($array as $value){$key = array_search($value, $array);print_r($key);print_r($value);}}$stop=microtime(true);$time = $stop - $start; print_r($time);

5.3秒:

$start=microtime(true);for ($i = 0; $i < 100000; $i++){foreach($array as $key=>$value){print_r($key);print_r($value);}}$stop=microtime(true);$time = $stop - $start; print_r($time);

所以没有性能提升?对于较大的数组,仍然存在差异:

$array = ["one"=>"un", "two"=>"deux", "three"=>"trois", "four"=>"quatre", "five"=>"cinq", "six"=>"six", "seven"=>"sept", "eight"=>"huit", "nine"=>"neuf", "ten"=>"dix"]; 
$array = ["one"=>"un", "two"=>"deux", "three"=>"trois"];
foreach ($array as $index=>$value){
    echo $index . ' : ' . $value . '<br />';
}

这确实很简单:

foreach ($array as $key => $value){
    echo $key;
    echo " ";
    echo $value;
    echo "<br />";
}