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'
);
//each返回数组中当前的键/值对并将数组指针向前移动一步
while ($elem = each($sports)) {
    echo $elem['key'].": ".$elem['value']."<br />";
}
?>

方法3:list & each

<?php
$sports = array(
    'football' => 'good',
    'swimming' => 'very well',
    'running'  => 'not good'
);
//list把数组中的值赋给一些变量
while (list($key, $value) = each($sports)) {
    echo $key.": ".$value."<br />";
}
?>

你可能感兴趣的:(PHP,遍历关联数组)