PHP中遍历关联数组的三种方法

六月ゝ 毕业季﹏ 提交于 2019-12-02 02:56:20

方法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 />";
}
?>

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!