
本文介绍一种高效方法,将具有父子关系的扁平数组转换为按 `name` 字段自动分组的多层嵌套树结构,支持同名节点聚合、递归子树分组及保持原始数据完整性。
在实际开发中(如菜单管理、组织架构、分类标签系统),我们常遇到需将数据库查出的扁平结构(含 id/parent_id)转为树形结构的需求。但当存在同名兄弟节点(如多个 "root1")且要求最终结果以 name 为键进行分组时,标准树构建逻辑不再适用——必须在构建完基础树后,再对每一层级执行「按 name 聚合 + 保留 children 结构」的双重递归处理。
以下是完整、可直接运行的解决方案:
$sibling) {
$id = $sibling['id'];
if (isset($grouped[$id])) {
$sibling['children'] = $fnBuilder($grouped[$id]);
}
$siblings[$k] = $sibling;
}
return $siblings;
};
return $fnBuilder($grouped[0] ?? []);
}
function groupedTree(array $tree): array
{
// 第三步:对任意层级树节点,按 'name' 聚合成关联数组
return array_reduce($tree, function (array $acc, array $node): array {
// 若存在 children,先递归处理其子树(保证深层 name 分组生效)
if (isset($node['children']) && is_array($node['children'])) {
$node['children'] = groupedTree($node['children']);
}
// 按 name 聚合:每个 name 对应一个节点数组
$acc[$node['name']][] = $node;
return $acc;
}, []);
}
// 示例数据
$flat = [
['id' => 1, 'parent_id' => 0, 'name' => 'root1'],
['id' => 2, 'parent_id' => 0, 'name' => 'root1'],
['id' => 3, 'parent_id' => 1, 'name' => 'ch-1'],
['id' => 4, 'parent_id' => 1, 'name' => 'ch-1'],
['id' => 5, 'parent_id' => 3, 'name' => 'ch-1-1'],
['id' => 6, 'parent_id' => 3, 'name' => 'ch-1-1'],
['id' => 7, 'parent_id' => 0, 'name' => 'root2'],
['id' => 8, 'parent_id' => 0, 'name' => 'root2'],
['id' => 9, 'parent_id' => 7, 'name' => 'ch3-1'],
['id' => 10, 'parent_id' => 7, 'name' => 'ch3-1']
];
// 执行两阶段转换
$tree = buildTree($flat);
$grouped = groupedTree($tree);
echo json_encode($grouped, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);✅ 关键设计说明:
- buildTree() 负责解决「父子关系建模」,输出标准 children 数组树;
- groupedTree() 是纯函数式递归器:它不修改原节点,仅按 'name' 键归集,并自动穿透 children 字段继续分组,实现全深度 name 聚合;
- 使用 array_reduce 替代 foreach,语义更清晰,避免手动索引管理;
- 支持空 children 或缺失 children 字段,健壮性高。
⚠️ 注意事项:
立即学习“PHP免费学习笔记(深入)”;
- 输入数组必须包含 id、parent_id 和 name 三个键,否则会触发 Notice;
- 若存在 parent_id 指向不存在 id 的节点(悬空引用),该节点将被忽略(因 $grouped[$id] 未定义);
- 输出为关联数组('root1' => [...]),不可直接用数字索引遍历,需用 foreach ($grouped as $name => $nodes);
- 如需兼容 JSON 序列化,确保所有 name 值为合法字符串(不含控制字符或非法 Unicode)。
该方案时间复杂度为 O(n)(两次线性扫描),空间复杂度 O(n),适用于数千节点规模的常规业务场景。











