其中數字索引數組和C語言中的陣列一樣,下標是為0,1,2…
而關聯數組下標可能是任意類型,與其它語言中的hash,map等結構相似。
下面介紹PHP中遍歷關聯數組的幾種方法:
方法1:foreach
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 />"; ?>
方法4:while() 和list(),each()配合使用。
<?php $urls= array('aaa','bbb','ccc','ddd'); while(list($key,$val)= each($urls)) { echo "This Site url is $val.<br />"; } ?>
顯示結果:
This Site url is aaa This Site url is bbb This Site url is ccc This Site url is ddd
方法5:for()
<?php $urls= array('aaa','bbb','ccc','ddd'); for ($i= 0;$i< count($urls); $i++){ $str= $urls[$i]; echo "This Site url is $str.<br />"; } ?>
顯示結果:
This Site url is aaa This Site url is bbb This Site url is ccc This Site url is ddd
以上是php遍歷關聯數組方法大全(foreach,list,each,list)的詳細內容。更多資訊請關注PHP中文網其他相關文章!