PHP 如何便捷 遍历 多维数组
时间: 2023-07-13 08:41:00 浏览: 81
指向数组元素的指针变量-指针编程与应用
PHP 提供了多种便捷的方式来遍历多维数组,以下是其中几种常用的方法:
1. foreach 循环:可以使用 foreach 循环来遍历多维数组。例如:
```php
$array = array(
array('name' => 'John', 'age' => 28),
array('name' => 'Mary', 'age' => 30),
array('name' => 'Tom', 'age' => 25)
);
foreach ($array as $value) {
echo $value['name'] . ' is ' . $value['age'] . ' years old.<br>';
}
```
输出:
```
John is 28 years old.
Mary is 30 years old.
Tom is 25 years old.
```
2. array_walk_recursive() 函数:可以使用 `array_walk_recursive()` 函数来遍历多维数组中的所有元素。例如:
```php
$array = array(
array('name' => 'John', 'age' => 28),
array('name' => 'Mary', 'age' => 30),
array('name' => array('first' => 'Tom', 'last' => 'Smith'), 'age' => 25)
);
function print_values($value, $key)
{
echo "$key: $value<br>";
}
array_walk_recursive($array, 'print_values');
```
输出:
```
name: John
age: 28
name: Mary
age: 30
first: Tom
last: Smith
age: 25
```
3. RecursiveArrayIterator 和 RecursiveIteratorIterator 类:可以使用 `RecursiveArrayIterator` 和 `RecursiveIteratorIterator` 类来遍历多维数组。例如:
```php
$array = array(
array('name' => 'John', 'age' => 28),
array('name' => 'Mary', 'age' => 30),
array('name' => array('first' => 'Tom', 'last' => 'Smith'), 'age' => 25)
);
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST);
foreach ($iterator as $key => $value) {
echo "$key: $value<br>";
}
```
输出:
```
name: John
age: 28
name: Mary
age: 30
first: Tom
last: Smith
age: 25
```
这些方法都可以方便地遍历多维数组,根据实际情况选择使用即可。
阅读全文