基于PHP遍历数组的方法汇总分析


Posted in PHP onJune 08, 2013

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

<?php
$colors= array('red','blue','green','yellow');
foreach ($colorsas$color){
echo "Do you like $color? <br />";
}
?>

显示结果:
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

2. while()
while() 通常和 list(),each()配合使用。
#example2:

<?php
$colors= array('red','blue','green','yellow');
while(list($key,$val)= each($colors)) {
echo "Other list of $val.<br />";
}
?>

显示结果:
Other list of red.
Other list of blue.
Other list of green.
Other list of yellow.

3. for()
#example3:

<?php
$arr= array ("0"=> "zero","1"=> "one","2"=> "two");
for ($i= 0;$i< count($arr); $i++){
$str= $arr[$i];
echo "the number is $str.<br />";
}
?>

显示结果:
the number is zero.
the number is one.
the number is two.

========= 以下是函数介绍 ==========
key()
mixed key(array input_array)
key()函数返回input_array中位于当前指针位置的键元素。
#example4

<?php
$capitals= array("Ohio"=> "Columbus","Towa"=> "Des Moines","Arizona"=> "Phoenix");
echo "<p>Can you name the capitals of these states?</p>";
while($key= key($capitals)) {
echo $key."<br />";
next($capitals);
//每个key()调用不会推进指针。为此要使用next()函数
}
?>

显示结果:
Can you name the capitals of these states?
Ohio
Towa
Arizona
reset()
mixed reset(array input_array)
reset()函数用来将input_array的指针设置回数组的开始位置。如果需要在一个脚本中多次查看或处理同一个数组,就经常使用这个函数,另外这个函数还常用于排序结束时。
#example5 - 在#example1上追加代码
<?php
$colors= array('red','blue','green','yellow');
foreach ($colorsas$color){
echo "Do you like $color? <br />";
}
reset($colors);
while(list($key,$val)= each($colors)) {
echo "$key=> $val<br />";
}
?>

显示结果:
Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?
0 => red
1 => blue
2 => green
3 => yellow
注意:将一个数组赋值给另一个数组时会重置原来的数组指针,因此在上例中如果我们在循环内部将 $colors 赋给了另一个变量的话将会导致无限循环。
例如将 $s1 = $colors; 添加到while循环内,再次执行代码,浏览器就会无休止地显示结果。
each()
array each(array input_array)
each()函数返回输入数组当前键/值对,并将指针推进一个位置。返回的数组包含四个键,键0和key包含键名,而键1和value包含相应的数据。如果执行each()前指针位于数组末尾,则返回FALSE。
#example6
<?php
$capitals= array("Ohio"=> "Columbus","Towa"=> "Des Moines","Arizona"=> "Phoenix");
$s1= each($capitals);
print_r($s1);
?>

显示结果:
Array ( [1] => Columbus [value] => Columbus [0] => Ohio [key] => Ohio )
current(),next(),prev(),end()
mixed current(array target_array)
current()函数返回位于target_array数组当前指针位置的数组值。与next()、prev()、和end()函数不同,current()不移动指针。
next()函数返回紧接着放在当前数组指针的下一个位置的数组值。
prev()函数返回位于当前指针的前一个位置的数组值,如果指针本来就位于数组的第一个位置,则返回FALSE。
end()函数将指针移向target_array的最后一个位置,并返回最后一个元素。
#example7
<?php
$fruits= array("apple","orange","banana");
$fruit= current($fruits); //return "apple"
echo $fruit."<br />";
$fruit= next($fruits); //return "orange"
echo $fruit."<br />";
$fruit= prev($fruits); //return "apple"
echo $fruit."<br />";
$fruit= end($fruits); //return "banana"
echo $fruit."<br />";
?>

显示结果:
apple
orange
apple
banana
=========== 下面来测试三种遍历数组的速度 ===========
一般情况下,遍历一个数组有三种方法,for、while、foreach。其中最简单方便的是foreach。下面先让我们来测试一下共同遍历一个有50000个下标的一维数组所耗的时间。
测试环境:
Intel Core Due2 2GHz
2GB 1067MHz DDR3
Mac OS X 10.5.7
Apache 2.0.59
MySQL 5.0.41
PHP 5.2.6
#example8
<?php
$arr= array();
for($i= 0; $i< 50000; $i++){
$arr[]= $i*rand(1000,9999);
}
function GetRunTime()
{
list($usec,$sec)=explode(" ",microtime());
return ((float)$usec+(float)$sec);
}
######################################
$time_start= GetRunTime();
for($i= 0; $i< count($arr); $i++){
$str= $arr[$i];
}
$time_end= GetRunTime();
$time_used= $time_end- $time_start;
echo 'Used time of for:'.round($time_used, 7).'(s)<br /><br />';
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)<br /><br />';
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)<br /><br />';
?>

测试结果:
Used time of for:0.0228429(s)
Used time of while:0.0544658(s)
Used time of foreach:0.0085628(s)
经过反复多次测试,结果表明,对于遍历同样一个数组,foreach速度最快,最慢的则是while。从原理上来看,foreach是对数组副本进行操作(通过拷贝数组),而while则通过移动数组内部指标进行操作,一般逻辑下认为,while应该比foreach快(因为foreach在开始执行的时候首先把数组复制进去,而while直接移动内部指标。),但结果刚刚相反。原因应该是,foreach是PHP内部实现,而while是通用的循环结构。所以,在通常应用中foreach简单,而且效率高。在PHP5下,foreach还可以遍历类的属性。
PHP 相关文章推荐
php数组函数序列之asort() - 对数组的元素值进行升序排序,保持索引关系
Nov 02 PHP
深入理解require与require_once与include以及include_once的区别
Jun 05 PHP
mcrypt启用 加密以及解密过程详细解析
Aug 07 PHP
浅谈PHP正则表达式中修饰符/i, /is, /s, /isU
Oct 21 PHP
php实现XSS安全过滤的方法
Jul 29 PHP
解决PHP里大量数据循环时内存耗尽的方法
Oct 10 PHP
PHP内存使用情况如何获取
Oct 10 PHP
Zend Framework教程之Bootstrap类用法概述
Mar 14 PHP
Laravel中Trait的用法实例详解
Mar 16 PHP
ThinkPHP框架里隐藏index.php
Apr 12 PHP
php的常量和变量实例详解
Jun 27 PHP
PHP实现的AES双向加密解密功能示例【128位】
Sep 03 PHP
深入for,while,foreach遍历时间比较的详解
Jun 08 #PHP
完美解决:Apache启动问题―(OS 10022)提供了一个无效的参数
Jun 08 #PHP
处理单名多值表单的详解
Jun 08 #PHP
探讨fckeditor在Php中的配置详解
Jun 08 #PHP
php创建基本身份认证站点的方法详解
Jun 08 #PHP
编写安全 PHP应用程序的七个习惯深入分析
Jun 08 #PHP
编写php应用程序实现摘要式身份验证的方法详解
Jun 08 #PHP
You might like
实现 win2003 下 mysql 数据库每天自动备份
2006/12/06 PHP
PHP 输出简单动态WAP页面
2009/06/09 PHP
PHP 输出缓存详解
2009/06/20 PHP
php xml留言板 xml存储数据的简单例子
2009/08/24 PHP
巧用php中的array_filter()函数去掉多维空值的代码分享
2012/09/07 PHP
yii实现级联下拉菜单的方法
2014/07/31 PHP
php生成xml时添加CDATA标签的方法
2014/10/17 PHP
PHP调用.NET的WebService 简单实例
2015/03/27 PHP
php基于协程实现异步的方法分析
2019/07/17 PHP
PHP 实现 JSON 数据的编码和解码操作详解
2020/04/22 PHP
clientX,pageX,offsetX,x,layerX,screenX,offsetLeft区别分析
2010/03/12 Javascript
jQuery移动页面开发中的触摸事件与虚拟鼠标事件简介
2015/12/03 Javascript
jQuery实现拖动剪裁图片作为头像
2016/12/28 Javascript
angular-cli修改端口号【angular2】
2017/04/19 Javascript
vue component组件使用方法详解
2017/07/14 Javascript
Node.js dgram模块实现UDP通信示例代码
2017/09/26 Javascript
Vue2.0 axios前后端登陆拦截器(实例讲解)
2017/10/27 Javascript
js 实现复选框只能选择一项的示例代码
2018/01/23 Javascript
《javascript设计模式》学习笔记五:Javascript面向对象程序设计工厂模式实例分析
2020/04/08 Javascript
jQuery 函数实例分析【函数声明、函数表达式、匿名函数等】
2020/05/19 jQuery
jQuery实现二级导航菜单的示例
2020/09/30 jQuery
vue实现滚动鼠标滚轮切换页面
2020/12/13 Vue.js
pandas数据分组和聚合操作方法
2018/04/11 Python
Django 中间键和上下文处理器的使用
2019/03/17 Python
Python GUI库PyQt5样式QSS子控件介绍
2020/02/25 Python
Python爬取阿拉丁统计信息过程图解
2020/05/12 Python
python 通过 pybind11 使用Eigen加速代码的步骤
2020/12/07 Python
最新优秀教师个人先进事迹材料
2014/05/06 职场文书
学习党的群众路线教育实践活动剖析材料
2014/10/13 职场文书
机关作风建设自查报告及整改措施
2014/10/21 职场文书
神农溪导游词
2015/02/11 职场文书
雨雪天气温馨提示
2015/07/15 职场文书
装修公司管理制度
2015/08/05 职场文书
2016教师廉洁教育心得体会
2016/01/13 职场文书
2019年中,最受大众欢迎的6本新书
2019/08/07 职场文书
MySQL中B树索引和B+树索引的区别详解
2022/03/03 MySQL