本文介绍一种高效方法,将具有父子关系的扁平数组转换为按 `name` 字段自动分组的多层嵌套树结构,支持同名节点聚合、递归子树处理,并保持原始数据完整性。
在实际开发中(如菜单管理、分类系统或权限树),我们常遇到需将数据库查出的扁平结构(含 id/parent_id)转为层级化树形数据的需求。而本例更进一步:不仅构建树,还需按 name 分组聚合——即相同 name 的兄弟/子孙节点应合并为一个键(如 "ch-1" => [...], [...]),而非简单追加到 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
{
return array_reduce($tree, function (array $acc, array $node): array {
// 递归处理子树:若存在 children,则先对其执行 groupedTree
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, 'paren
t_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);
$result = groupedTree($tree);
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);通过上述两步法,你不仅能获得清晰的 ["name" => [...]] 分组格式,还能无缝保留完整的父子路径信息,为后续 JSON API 输出、Vue/React 动态菜单或 ACL 权限校验提供理想的数据基础。