首頁 >後端開發 >php教程 >php遍歷關聯數組方法大全(foreach,list,each,list)

php遍歷關聯數組方法大全(foreach,list,each,list)

伊谢尔伦
伊谢尔伦原創
2017-06-22 15:47:302546瀏覽

在PHP中陣列分為兩類: 數字索引陣列和關聯陣列。

其中數字索引數組和C語言中的陣列一樣,下標是為0,1,2…
而關聯數組下標可能是任意類型,與其它語言中的hash,map等結構相似。


下面介紹PHP中遍歷關聯數組的幾種方法:
方法1:foreach

foreach ()是用來遍歷陣列中資料的最簡單有效的方法。

<?php 
$sports = array( 
&#39;football&#39; => &#39;good&#39;, 
&#39;swimming&#39; => &#39;very well&#39;, 
&#39;running&#39; => &#39;not good&#39;); 
foreach ($sports as $key => $value) { 
echo $key.": ".$value."<br />"; 
?>

輸出結果:

football: good 
swimming: very well 
running: not good

方法2:each

<?php 
$sports = array( 
&#39;football&#39; => &#39;good&#39;, 
&#39;swimming&#39; => &#39;very well&#39;, 
&#39;running&#39; => &#39;not good&#39;); 
while ($elem = each($sports)) { 
echo $elem[&#39;key&#39;].": ".$elem[&#39;value&#39;]."<br />"; 
?>

方法3:list & each 

<?php 
$sports = array( 
&#39;football&#39; => &#39;good&#39;, 
&#39;swimming&#39; => &#39;very well&#39;, 
&#39;running&#39; => &#39;not good&#39;); 
while (list($key, $value) = each($sports)) { 
echo $key.": ".$value."<br />"; 
?>

方法4:while() 和list(),each()配合使用。

<?php
    $urls= array(&#39;aaa&#39;,&#39;bbb&#39;,&#39;ccc&#39;,&#39;ddd&#39;);
    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(&#39;aaa&#39;,&#39;bbb&#39;,&#39;ccc&#39;,&#39;ddd&#39;);
    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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn