在PHP中數組分為兩類: 數字索引數組和關聯數組。其中數字索引數組和C語言中的數組一樣,下標是為0,1,2…而關聯數組下標可能是任意類型,與其它語言中的hash,map等結構相似。
下面介紹PHP中遍歷關聯數組的三種方法:
<?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
<?php $sports = array( 'football' => 'good', 'swimming' => 'very well', 'running' => 'not good' ); while ($elem = each($sports)) { echo $elem['key'].": ".$elem['value']."<br />"; } ?>
程序運行結果:
football: good swimming: very well running: not good
<?php $sports = array( 'football' => 'good', 'swimming' => 'very well', 'running' => 'not good' ); while (list($key, $value) = each($sports)) { echo $key.": ".$value."<br />"; } ?>
程序運行結果:
football: good swimming: very well running: not good