php遍历关联数组的三种方法。
方法1:foreach
复制代码 代码示例:
<?php
$sports = array(
'football' => 'good',
'swimming' => 'very well',
'running' => 'not good');
foreach ($sports as $key => $value) {
echo $key.": ".$value."<br />";
?>
输出结果:
football: good
swimming: very well
running: not good
方法2:each
复制代码 代码示例:
<?php
$sports = array(
'football' => 'good',
'swimming' => 'very well',
'running' => 'not good');
while ($elem = each($sports)) {
echo $elem['key'].": ".$elem['value']."<br />";
?>
方法3:list & each
复制代码 代码示例:
<?php
$sports = array(
'football' => 'good',
'swimming' => 'very well',
'running' => 'not good');
while (list($key, $value) = each($sports)) {
echo $key.": ".$value."<br />";
?>
介绍完了三种遍历php数组的方法,哪个方法更好呢?
这个大家可以找个复杂的数据,进行下效率测试,就明白了。