Php 简明教程

PHP - Foreach Loop

PHP 中的 foreach 构造函数专门用于迭代数组。如果你在数据类型不同的变量上尝试使用它,PHP 会报错。

The foreach construct in PHP is specially meant for iterating over arrays. If you try to use it on a variable with a different data type, PHP raises an error.

PHP 中的 foreach 循环可用于索引数组和关联数组。有两种使用语法可用——

The foreach loop in PHP can be used with indexed array as well as associative array. There are two types of usage syntaxes available −

foreach (array as $value) {
   statements
}

当你想迭代索引数组时,上述方法很有用。下述语法更适合关联数组。

The above method is useful when you want to iterate an indexed array. The syntax below is more suitable for associative arrays.

foreach (array as $key => $value) {
   statements
}

然而,这两种方法都适用于索引数组,因为数组中项目索引也充当键。

However, both these approaches work well with indexed array, because the index of an item in the array also acts as the key.

Using "foreach" Loop with an Indexed Array

上述第一种类型的语法在 foreach 关键词前面显示了一个括号。要遍历的数组的名称之后是 as 关键词,然后再是变量。

The first type of syntax above shows a parenthesis in front of the foreach keyword. The name of the array to be traversed is then followed by the "as" keyword and then a variable.

当第一个迭代开始时,第一个数组元素分配给变量。循环块结束后,变量获取下一个元素的值,并重复循环体中的语句,直到数组中的元素耗尽。

When the fist iteration starts, the first element in the array is assigned to the variable. After the looping block is over, the variable takes the value of the next element and repeats the statements in the loop body till the elements in the array are exhausted.

foreach 循环的典型用法如下——

A typical use of foreach loop is as follows −

<?php
   $arr = array(10, 20, 30, 40, 50);
   foreach ($arr as $val) {
      echo "$val \n";
   }
?>

Example

PHP 提供了一个非常有用的 array_search() 函数,它返回给定值的键。由于索引本身是索引数组中的键,因此,每个 $val 的 array_search() 会返回每个值的基于零的索引。以下代码展示它是如何工作的——

PHP provides a very useful function in array_search() which returns the key of a given value. Since the index itself is the key in an indexed array, the array_search() for each $val returns the zero based index of each value. The following code demonstrates how it works −

<?php
   $arr = array(10, 20, 30, 40, 50);

   foreach ($arr as $val) {
      $index = array_search($val, $arr);
      echo "Element at index $index is $val \n";
   }
?>

它将生成以下 output

It will produce the following output

Element at index 0 is 10
Element at index 1 is 20
Element at index 2 is 30
Element at index 3 is 40
Element at index 4 is 50

Example

foreach 语法的第二个变体将数组中的每个元素解压缩到两个变量中:一个用于 key ,一个用于 value

The second variation of foreach syntax unpacks each element in the array into two variables: one for the key and one for value.

由于在索引数组的情况下,索引本身充当键,因此 $k 变量会连续获取数组中每个元素的增量索引。

Since the index itself acts as the key in case of an indexed array, the $k variable successively takes the incrementing index of each element in the array.

<?php
   $arr = array(10, 20, 30, 40, 50);
   foreach ($arr as $k=>$v) {
      echo "Key: $k => Val: $v \n";
   }
?>

它将生成以下 output

It will produce the following output

Key: 0 => Val: 10
Key: 1 => Val: 20
Key: 2 => Val: 30
Key: 3 => Val: 40
Key: 4 => Val: 50

Iterating an Associative Array using "foreach" Loop

关联数组是由键值对收集的。若要迭代关联数组,第二种 foreach 语法变体是合适的。数组中的每个元素都解压缩到两个变量中,每个变量都获取键及其值。

An associative array is a collection of key-value pairs. To iterate through an associative array, the second variation of foreach syntax is suitable. Each element in the array is unpacked in two variables each taking up the value of key and its value.

Example

这里有一个使用 foreach 循环遍历各州及其对应首府的数组的示例。

Here is an example in which an array of states and their respective capitals is traversed using the foreach loop.

<?php
   $capitals = array(
      "Maharashtra"=>"Mumbai", "Telangana"=>"Hyderabad",
      "UP"=>"Lucknow", "Tamilnadu"=>"Chennai"
   );

   foreach ($capitals as $k=>$v) {
      echo "Capital of $k is $v \n";
   }
?>

它将生成以下 output

It will produce the following output

Capital of Maharashtra is Mumbai
Capital of Telangana is Hyderabad
Capital of UP is Lucknow
Capital of Tamilnadu is Chennai

然而,你仍可以使用 foreach 陈述的第一个版本,其中仅数组中每个键值对的值存储在变量中。然后使用之前使用过的 array_search() 函数获取对应于该值的关键。

However, you can still use the first version of foreach statement, where only the value from each key-value pair in the array is stored in the variable. We then obtain the key corresponding to the value using the array_search() function that we had used before.

<?php
   $capitals = array(
      "Maharashtra"=>"Mumbai", "Telangana"=>"Hyderabad",
      "UP"=>"Lucknow", "Tamilnadu"=>"Chennai"
   );

   foreach ($capitals as $pair) {
      $cap = array_search($pair, $capitals);
      echo "Capital of $cap is $capitals[$cap] \n";
   }
?>

Iterating a 2D Array using "foreach" Loop

可以在 PHP 中声明多维数组,其中数组中的每个元素都是另一个数组本身。请注意外部数组和子数组都可以是索引数组或关联数组。

It is possible to declare a multi-dimensional array in PHP, wherein each element in an array is another array itself. Note that both the outer array as well as the sub-arry may be an indexed array or an associative array.

在下面的示例中,我们有一个二维数组,它可以称为数组或数组。我们需要嵌套循环以遍历嵌套数组结构,如下所示——

In the example below, we have a two-dimensional array, which can be called as an array or arrays. We need nested loops to traverse the nested array structure as follows −

<?php
   $twoD = array(
      array(1,2,3,4),
      array("one", "two", "three", "four"),
      array("one"=>1, "two"=>2, "three"=>3)
   );

   foreach ($twoD as $idx=>$arr) {
      echo "Array no $idx \n";
      foreach ($arr as $k=>$v) {
         echo "$k => $v" . "\n";
      }
      echo "\n";
   }
?>

它将生成以下 output

It will produce the following output

Array no 0
0 => 1
1 => 2
2 => 3
3 => 4

Array no 1
0 => one
1 => two
2 => three
3 => four

Array no 2
one => 1
two => 2
three => 3