PHP中遍历数组的方法-创新互联

PHP中遍历数组的方法?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

创新互联长期为数千家客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为石龙企业提供专业的成都网站设计、做网站,石龙网站改版等技术服务。拥有10年丰富建站经验和众多成功案例,为您定制开发。

第一、foreach()


foreach()是一个用来遍历数组中数据的最简单有效的方法。


";
    } 
?>

显示结果:

This Site url is aaa 
This Site url is bbb 
This Site url is ccc 
This Site url is ddd

第二、while() 和 list(),each()配合使用。

"; 
    } 
?>

显示结果:

This Site url is aaa
This Site url is bbb
This Site url is ccc
This Site url is ddd

第三、for()运用for遍历数组

"; 
    } 
?>

显示结果:

This Site url is aaa 
This Site url is bbb 
This Site url is ccc 
This Site url is ddd

有时候有人也在问这几种遍历数组的方法哪个更快捷些呢,下面做个简单的测试就明白了

下面来测试三种遍历数组的速度

一般情况下,遍历一个数组有三种方法,for、while、foreach。其中最简单方便的是foreach。下面先让我们来测试一下共同遍历一个有50000个下标的一维数组所耗的时间。

'; 
  unset($str, $time_start, $time_end, $time_used); 
  ###################################### 
  $time_start= GetRunTime(); 
  while(list($key, $val)= each($arr)){ 
  $str= $val; 
  } 
  $time_end= GetRunTime(); 
  $time_used= $time_end- $time_start; 
  echo 'Used time of while:'.round($time_used, 7).'(s)'; 
  unset($str, $key, $val, $time_start, $time_end, $time_used); 
  ###################################### 
  $time_start= GetRunTime(); 
  foreach($arr as$key=> $val){ 
  $str= $val; 
  } 
  $time_end= GetRunTime(); 
  $time_used= $time_end- $time_start; 
  echo 'Used time of foreach:'.round($time_used, 7).'(s)'; 
?>

测试结果:

Used time of for:0.0228429(s) 
Used time of while:0.0544658(s) 
Used time of foreach:0.0085628(s)

看完上述内容,你们掌握PHP中遍历数组的方法的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


当前文章:PHP中遍历数组的方法-创新互联
当前网址:http://pwwzsj.com/article/dcdcic.html