處理表單巢狀資料、解析 JSON/API 回應、建立樹狀選單、深度搜尋特定鍵值等,皆需遍歷多維陣列。
<?php
function walkArrayRecursive(array $array, callable $callback, string $path = ''): void
{
foreach ($array as $key => $value) {
$currentPath = $path ? "$path[$key]" : "[$key]";
if (is_array($value)) {
walkArrayRecursive($value, $callback, $currentPath);
} else {
$callback($currentPath, $value);
}
}
}
// 使用範例
$data = [
'user' => ['name' => 'Alice', 'age' => 28],
'settings' => ['theme' => 'dark', 'lang' => 'zh-TW'],
];
walkArrayRecursive($data, function (string $path, $value) {
echo "$path = $value\n";
});
/*
[user][name] = Alice
[user][age] = 28
[settings][theme] = dark
[settings][lang] = zh-TW
*/
<?php
$data = [
'a' => [1, 2, ['x', 'y']],
'b' => 3,
];
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($data),
RecursiveIteratorIterator::SELF_FIRST // 先處理父層再處理子層
);
foreach ($iterator as $key => $value) {
$depth = $iterator->getDepth();
$path = implode('][', array_map(fn($k) => "[$k]", iterator_to_array(new RecursiveTreeIterator($iterator, RecursiveTreeIterator::BYPASS_CURRENT))));
// 簡化:直接輸出鍵值與深度
echo str_repeat(' ', $depth) . "[$key] => $value\n";
}
<?php
function flattenArray(array $array): Generator
{
foreach ($array as $key => $value) {
if (is_array($value)) {
yield from flattenArray($value);
} else {
yield $key => $value;
}
}
}
foreach (flattenArray($hugeArray) as $key => $value) {
// 逐一處理,不一次載入所有鍵值到記憶體
process($key, $value);
}
// 搜尋所有 'email' 鍵
function findKey(array $array, string $targetKey): array
{
$results = [];
walkArrayRecursive($array, function ($path, $value) use ($targetKey, &$results) {
if (basename($path) === "[$targetKey]") {
$results[$path] = $value;
}
});
return $results;
}
// 扁平化為單層陣列(鍵名以點號串接)
function flattenToDotNotation(array $array, string $prefix = ''): array
{
$result = [];
foreach ($array as $key => $value) {
$newKey = $prefix ? "$prefix.$key" : $key;
if (is_array($value)) {
$result += flattenToDotNotation($value, $newKey);
} else {
$result[$newKey] = $value;
}
}
return $result;
}