在PHP中數組分為兩類: 數字索引數組和關聯數組。
其中數字索引數組和C語言中的數組一樣,下標是為0,1,2…
而關聯數組下標可能是任意類型,與其它語言中的hash,map等結構相似。
下面介紹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 />";
?>