You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将单表存储的父子层级分类数据转换为多层嵌套数组?

解决方案

你当前的代码仅能生成二级结构,核心问题是每次判断到父级存在时,只直接写入了顶层数组下的subCategory,且每次赋值会覆盖已有子分类,同时递归查找父级的方式效率很低。你可以使用引用+扁平索引的方案实现无限层级嵌套,逻辑简单且性能更高,不需要额外的multiKeyExists方法:

public function getList(int $topParentId): array
{
    // 第一步:将全部分类数据整理为以ID为键的扁平数组,提前初始化子分类字段
    $flatCategory = [];
    foreach ($result as $value) { // $result为你查询到的全部分类原始数据
        $flatCategory[$value['id']] = [
            'id' => $value['id'],
            'title' => $value['title'],
            'parent_id' => $value['parent_id'],
            'subCategory' => []
        ];
    }

    // 第二步:遍历扁平数组,将每个分类挂载到对应父级的子分类下
    $tree = [];
    foreach ($flatCategory as $id => &$item) {
        $parentId = (int)$item['parent_id'];
        if ($parentId === $topParentId) {
            // 匹配顶级父分类,直接加入结果树
            $tree[$id] = &$item;
        } elseif (isset($flatCategory[$parentId])) {
            // 父分类存在,挂载到父分类的子分类数组中
            $flatCategory[$parentId]['subCategory'][$id] = &$item;
        }
    }
    // 销毁引用避免后续操作出现异常
    unset($item);

    return $tree;
}

如果你需要输出你示例中的缩进列表结构,可以搭配以下递归打印方法:

public function printCategoryTree(array $tree, int $indentLevel = 0): void
{
    $indentPrefix = str_repeat('  ', $indentLevel);
    foreach ($tree as $item) {
        echo "{$indentPrefix}- {$item['id']}" . PHP_EOL;
        if (!empty($item['subCategory'])) {
            $this->printCategoryTree($item['subCategory'], $indentLevel + 1);
        }
    }
}

调用方式:

$tree = $this->getList(87);
$this->printCategoryTree($tree);

内容的提问来源于stack exchange,提问作者user1687891

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 01:54:08