超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<currentend>
Last updated: Fri, 22 Jun 2007

each

(PHP 3, PHP 4 , PHP 5)

each --  返回数组中当前的键/值对并将数组指针向前移动一步

说明

array each ( array array)

返回 array 数组中当前指针位置的键/值对并向前移动数组指针。键值对被返回为四个单元的数组,键名为 01keyvalue。单元 0key 包含有数组单元的键名,1value 包含有数据。

如果内部指针越过了数组的末端,则 each() 返回 FALSE

例子 1. each() 例子

<?php
$foo
= array ("bob", "fred", "jussi", "jouni", "egon", "marliese");
$bar = each ($foo);
print_r($bar);
?>

$bar 现在包含有如下的键/值对:

Array
{
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
}

<?php
$foo
= array ("Robert" => "Bob", "Seppo" => "Sepi");
$bar = each ($foo);
print_r($bar);
?>

$bar 现在包含有如下的键/值对:

Array
{
    [1] => Bob
    [value] => Bob
    [0] => Robert
    [key] => Robert
}

each() 经常和 list() 结合使用来遍历数组,例如:

例子 2. 用 each() 遍历数组

<?php
$fruit
= array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
reset ($fruit);
while (list (
$key, $val) = each ($fruit)) {
   echo
"$key => $val\n";
}
/* Outputs:

a => apple
b => banana
c => cranberry

*/
?>

在执行 each() 之后,数组指针将停留在数组中的下一个单元或者当碰到数组结尾时停留在最后一个单元。如果要再用 each 遍历数组,必须使用 reset()

注意

因为将一个数组赋值给另一个数组时会重置原来的数组指针,因此在上边的例子中如果我们在循环内部将 $fruit 赋给了另一个变量的话将会导致无限循环。

参见 key()list()current()reset()next()prev()foreach




add a note add a note User Contributed Notes
each
php-traversing-matrices at mark dot datasys dot net
29-Nov-1999 12:47
Traversing multidimensional arrays is
easy, especially if you know how many dimensions are involved. Suppose you have a structure returned from a database query, such as

$returned_rows[$row_number][$field_name]

To walk through each field, you
might try this:

while (
  list($row_number, $row_array)
    = each($query_result_array)
  ) {
  while (
    list($field_name, $field_value)
       = each($row_array)
  ) {
     ##
     ## $row_number has the
     ## current row number,
     ## $field_name hsa the current  
     ## field' name,
     ## $field_value has the current         ## field's value
   }
 }
}

<currentend>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22