處理多維陣列是高頻需求。本文展示兩種核心寫法:釐清已知結構用雙層 foreach、結構不定深度用遞迴函數。
<?php
$a = [
'fruits' => ['a' => 'orange', 'b' => 'grape', 'c' => 'apple'],
'numbers' => [1, 2, 3, 4, 5, 6],
'holes' => ['first', 5 => 'second', 'third'],
];
<?php
foreach ($a as $listKey => $things) {
if (is_array($things)) {
foreach ($things as $newKey => $value) {
echo "key: $newKey
value: $value
";
}
}
}
<?php
function flattenArray($array, &$result = []) {
foreach ($array as $key => $value) {
if (is_array($value)) {
flattenArray($value, $result);
} else {
$result[] = $value;
}
}
return $result;
}
$flat = flattenArray($a);
print_r($flat);
/*
Array
(
[0] => orange
[1] => grape
[2] => apple
[3] => 1
[4] => 2
[5] => 3
[6] => 4
[7] => 5
[8] => 6
[9] => first
[10] => second
[11] => third
)
*/
<?php
function walkArray($array, $path = '', &$result = []) {
foreach ($array as $key => $value) {
$currentPath = $path ? "$path.$key" : (string)$key;
if (is_array($value)) {
walkArray($value, $currentPath, $result);
} else {
$result[$currentPath] = $value;
}
}
return $result;
}
$walked = walkArray($a);
/*
Array
(
[fruits.a] => orange
[fruits.b] => grape
[fruits.c] => apple
[numbers.0] => 1
...
)
*/
| 場景 | 推薦方法 | 理由 |
|---|---|---|
| 固定二維陣列 | 雙層 foreach | 零函數呼叫開銷,最快 |
| 不定深度/動態結構 | 遞迴函數 | 通用性強,程式碼可維護 |
| 需保留鍵名路徑 | 帶路徑遞迴 | 方便後續按路徑查找/更新 |
| 超大陣列(萬級+) | 迭代器/Generator | 避免遞迴堆疊溢出,記憶體友善 |
array_walk_recursive():內建遞迴遍歷,效能優於自寫遞迴RecursiveArrayIterator + RecursiveIteratorIterator:SPL 迭代器,物件導向風格<?php
// 內建遞迴遍歷範例
$result = [];
array_walk_recursive($a, function($value, $key) use (&$result) {
$result[] = $value;
});