在PHP中数组分为两类: 数字索引数组和关联数组。
其中数字索引数组和C语言中的数组一样,下标是为0,1,2…
而关联数组下标可能是任意类型,与其它语言中的hash,map等结构相似。

下面介绍PHP中遍历关联数组的三种方法:
方法1:foreach

1 <?php
2 $sports = array(
3     'football' => 'good',
4     'swimming' => 'very well',
5     'running'  => 'not good');
6 foreach ($sports as $key => $value) {
7     echo $key.": ".$value."<br />";
8 ?>

输出结果:

football: goodswimming: very wellrunning: not good

方法2:each

1 <?php
2 $sports = array(
3     'football' => 'good',
4     'swimming' => 'very well',
5     'running'  => 'not good');
6 while ($elem = each($sports)) {
7     echo $elem['key'].": ".$elem['value']."<br />";
8 ?>

方法3:list & each

1 <?php
2 $sports = array(
3     'football' => 'good',
4     'swimming' => 'very well',
5     'running'  => 'not good');
6 while (list($key, $value) = each($sports)) {
7     echo $key.": ".$value."<br />";
8 ?>