有關php數組的分類,PHP數組分為:數字索引數組和關聯數組。
其中數字索引數組和C語言中的數組一樣,下標是為0,1,2…
而關聯數組下標可能是任意類型,與其它語言中的hash,map等結構相似。
PHP遍歷關聯數組的三種方法,供大家參考。
方法1:foreach
復制代碼 代碼示例:
$sports = array(
'football' => 'good',
'swimming' => 'very well',
'running'? => 'not good');
foreach ($sports as $key => $value) {
echo $key.": ".$value."
";
} //by www.jbxue.com
?>
輸出結果:
football: goodswimming: very wellrunning: not good
方法2:each
復制代碼 代碼示例:
$sports = array(
'football' => 'good',
'swimming' => 'very well',
'running'? => 'not good');
while ($elem = each($sports)) {
echo $elem['key'].": ".$elem['value']."
";
}
?>
方法3:list & each
復制代碼 代碼示例:
$sports = array(
'football' => 'good',
'swimming' => 'very well',
'running'? => 'not good');
while (list($key, $value) = each($sports)) {
echo $key.": ".$value."
";
}
?>
學php教程,就來腳本學堂,祝大家學習進步。