萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> PHP 遍歷數組語句總結(foreach,for,list,each)

PHP 遍歷數組語句總結(foreach,for,list,each)

在php中遍歷循環讀出數組的方法有幾種,foreach,for,list,each,while都是可以的,只是那種更適合用來遍歷數組了。

foreach來訪問, 遍歷的順序是固定的麼? 以什麼順序遍歷呢?

比如:

 代碼如下 復制代碼

<?php
$colors= array('red','blue','green','yellow');
foreach ($colors as $color){
//add your codes
}
?>

例2

$capitals= array("Ohio"=> "Columbus","Towa"=> "Des Moines","Arizona"=> "Phoenix");
foreach($capitals as  $key=> $val){
//add your codes
}
 

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

each() 函數遍歷數組

例子 1

 代碼如下 復制代碼

<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
print_r (each($people));
?>

輸出:

Array ( [1] => Peter [value] => Peter [0] => 0 [key] => 0 )

子 2
each() 經常和 list() 結合使用來遍歷數組。本例與上例類似,不過循環輸出了整個數組:

 代碼如下 復制代碼

<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");

reset($people);

while (list($key, $val) = each($people))
  {
  echo "$key => $val<br />";
  }
?>

輸出:

0 => Peter
1 => Joe
2 => Glenn
3 => Cleveland


多維數組的遞歸遍歷

 代碼如下 復制代碼

<?php
/*
*  -------------------------------------------------
*   Author :
*   Url    : www.111cn.net*   Date   : 2011-03-09
*  -------------------------------------------------
*/
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);
?>

結果

Array
(
    [1] => Array
        (
            [0] => 11
            [1] => 12
            [2] => 13
            [14] => Array
                (
                    [0] => 141
                    [1] => 142
                )

        )

    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
)
11
12
13
141
142
2
3
4
5

copyright © 萬盛學電腦網 all rights reserved