PHP 遍历数组语句总结(foreach,for,list,each)
来源:程序员人生 发布时间:2014-05-03 13:14:12 阅读次数:2616次
在php中遍历循环读出数组的方法有几种,foreach,for,list,each,while都是可以的,只是那种更适合用来遍历数组了。
foreach来访问,遍历的顺序是固定的么? 以什么顺序遍历呢?
比如:代码如下:
- <?php
- $colors= array('red','blue','green','yellow');
- foreach ($colors as $color){
-
- }
- ?>
例2,代码如下:
- $capitals= array("Ohio"=> "Columbus","Towa"=> "Des Moines","Arizona"=> "Phoenix");
- foreach($capitals as $key=> $val){
-
- }
while()
while() 通常和 list(),each()配合使用,实例代码如下:
- <?php
- $colors = array('red','blue','green','yellow');
- while(list($key,$val) = each($colors)) {
- echo "Other list of $val.<br />";
- }
- ?>
-
-
-
-
-
-
-
3. for(),实例代码如下:
- <?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 />";
- }
- ?>
-
-
-
-
-
-
以下是函数介绍:
key()
mixed key(array input_array)
key()函数返回input_array中位于当前指针位置的键元素。
实例代码如下:
- <?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);
-
- }
- ?>
-
-
-
-
-
-
each() 函数遍历数组
例子1,代码如下:
- <?php
- $people = array("Peter", "Joe", "Glenn", "Cleveland");
- print_r (each($people));
- ?>
-
-
例子2,代码如下:
each() 经常和 list() 结合使用来遍历数组,本例与上例类似,不过循环输出了整个数组,代码如下:
- <?php
- $people = array("Peter", "Joe", "Glenn", "Cleveland");
- reset($people);
- while (list($key, $val) = each($people))
- {
- echo "$key => $val<br />";
- }
- ?>
-
-
-
-
-
-
-
多维数组的递归遍历,代码如下:
- <?php
-
-
-
-
-
-
- function arr_foreach ($arr)
- {
- if (!is_array ($arr))
- {
- return false;
- }
-
- foreach ($arr as $key => $val )
- {
- if (is_array ($val))
- {
- arr_foreach ($val);
- }
- else
- {
- echo $val.'<br/>';
- }
- }
- }
- $arr1 = array (1=>array(11,12,13,14=>array(141,142)),2,3,4,5);
- echo '<pre>';
- print_r($arr1);
- echo '<pre>';
- arr_foreach ($arr1);
- ?>
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠