如何用递归将含父子关系、标量数据不一致的多维数组转为扁平化二维数组
递归扁平化树形数组的解决方案
原代码的问题
- 参数传递错误:
$i和$branch采用值传递,递归调用时内部修改的是参数副本,无法同步到外层,导致数组元素索引混乱、子节点结果丢失 - 字段处理不兼容:硬编码取
title字段,未处理示例中存在的identifier特殊字段(如id为5556的元素)
修正后的代码
function flattenTree(array $elements) { $result = []; foreach ($elements as $element) { // 提取核心字段,兼容title和identifier两种标题字段 $item = ['id' => $element['id']]; if (isset($element['title'])) { $item['title'] = $element['title']; } elseif (isset($element['identifier'])) { $item['identifier'] = $element['identifier']; } $result[] = $item; // 递归处理子节点,合并结果到主数组 if (!empty($element['children'])) { $result = array_merge($result, flattenTree($element['children'])); } } return $result; } // 调用示例 $tree = [ 'children' => [ [ 'id' => 123, 'title' => 'test', 'children' => [ [ 'id' => 345, 'title' => 'test 1', 'children' => [], ], [ 'id' => 567, 'title' => 'test 2', 'children' => [ [ 'id' => 789, 'title' => 'test 3', 'children' => [], ], [ 'id' => 333, 'title' => 'tset 4', 'children' => [ [ 'id' => 222, 'title' => 'test 5', 'children' => [], ], [ 'id' => 111, 'title' => 'test 55', 'children' => [], ], [ 'id' => 444, 'title' => 'test 556', 'children' => [], ], [ 'id' => 666, 'title' => 'test44', 'children' => [], ], ], ], [ 'id' => '5556', 'identifier' => 'test 2', 'children' => [ [ 'id' => 888, 'title' => 'test 2', 'children' => [], ], [ 'id' => 255, 'title' => 'tset', 'children' => [], ], [ 'id' => 454, 'title' => 'warm-up-5837', 'children' => [], ], ], ], ], ], ], ], ], ]; $result = flattenTree($tree['children']); print_r($result);
代码说明
- 移除冗余的
$i索引参数,直接用$result[]追加元素,避免索引混乱 - 通过
array_merge合并递归处理的子节点结果,确保所有层级元素都被收集 - 增加字段兼容逻辑,自动识别
title或identifier字段,适配示例中的特殊元素 - 调用时需传入根节点的
children数组,匹配原树形结构的顶层格式
执行后将得到与预期一致的扁平化二维数组,元素顺序与树形结构的深度优先遍历顺序一致。
内容的提问来源于stack exchange,提问作者Bhumi Shah
相关产品推荐
相关产品推荐

