首页 >后端开发 >php教程 >php遍历关联数组方法大全(foreach,list,each,list)

php遍历关联数组方法大全(foreach,list,each,list)

伊谢尔伦
伊谢尔伦原创
2017-06-22 15:47:302533浏览

在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