如何在 PHP 中将扁平数组构建为按名称分组的嵌套树结构

如何在 PHP 中将扁平数组构建为按名称分组的嵌套树结构

本文介绍一种高效方法,将具有父子关系的扁平数组转换为按 `name` 字段自动分组的多层嵌套树结构,支持同名节点聚合、递归子树处理,并保持原始数据完整性。

在实际开发中(如菜单管理、分类系统或权限树),我们常遇到需将数据库查出的扁平结构(含 id/parent_id)转为层级化树形数据的需求。而本例更进一步:不仅构建树,还需按 name 分组聚合——即相同 name 的兄弟/子孙节点应合并为一个键(如 “ch-1” => […], […]),而非简单追加到 children 数组中。这提升了数据可读性与前端渲染灵活性。

核心思路:两阶段处理

  1. 第一阶段:使用经典递归方式构建标准树结构(基于 id/parent_id 关系);
  2. 第二阶段:对已生成的树进行深度优先遍历,用 array_reduce 按 name 键重组每一层节点,同时递归处理其 children(若存在)。

以下是完整可运行的实现代码:

MetaVoice

MetaVoice

AI实时变声工具

下载

 $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, '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);
$result = groupedTree($tree);

echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

注意事项与最佳实践

  • 健壮性增强:建议在 buildTree() 中添加 isset($grouped[0]) 判断,避免空根导致 Notice;
  • 性能优化:对于超大数据集(>10,000 条),可改用迭代+模拟递归,防止 PHP 栈溢出;
  • ⚠️ name 冲突风险:确保业务逻辑允许同名节点共存;若需唯一标识,应在 groupedTree() 中加入 id 辅助键(如 $acc[$node[‘name’] . ‘_’ . $node[‘id’]]);
  • ? 扩展性提示:该方案天然支持任意深度嵌套,且 groupedTree() 可独立复用于任何已有树结构,无需依赖原始扁平数组。

通过上述两步法,你不仅能获得清晰的 [“name” => […]] 分组格式,还能无缝保留完整的父子路径信息,为后续 JSON API 输出、Vue/React 动态菜单或 ACL 权限校验提供理想的数据基础。

https://www.php.cn/faq/1963597.html

发表回复

Your email address will not be published. Required fields are marked *