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

PHP根据parentid递归构建带pages字段的层级数组问题排查

PHP无限层级分类构建代码问题排查

存在的两个核心错误

  • 字段赋值对象错误:函数buildSubs内部给子节点挂载字段时,误把整个传入数组$elms当做赋值对象,实际应该给当前遍历到的单条元素$elm添加pages字段
  • 调用参数错误:你调用函数时传入的父ID为1,只会筛选出父ID为1的元素(即id=2的条目),如果要从根节点(parentid=0)开始构建完整层级,调用时父ID应该传0

修正后完整代码

<?php
$indexes = [
    ['id' => 1, 'parentid' => 0, 'route' => 'root', 'title' => 'root'],
    ['id' => 2, 'parentid' => 1, 'route' => 'parent', 'title' => 'parent'],
    ['id' => 3, 'parentid' => 2, 'route' => 'child', 'title' => 'child']
];
// 根节点parentid为0,调用时传0
$indexes = buildSubs($indexes, 0);
var_dump($indexes);

function buildSubs(array $elms, int $parentId = 0)
{
    $branch = [];
    foreach ($elms as $elm) {
        if ($elm['parentid'] == $parentId) {
            $children = buildSubs($elms, $elm['id']);
            if ($children) {
                // 给当前元素加pages字段,不要修改整个$elms数组
                $elm['pages'] = $children;
            }
            $branch[] = $elm;
        }
    }
    return $branch;
}

运行输出结果

输出结构完全符合预期,格式化后如下:

array(1) {
  [0]=>
  array(5) {
    ["id"]=>
    int(1)
    ["parentid"]=>
    int(0)
    ["route"]=>
    string(4) "root"
    ["title"]=>
    string(4) "root"
    ["pages"]=>
    array(1) {
      [0]=>
      array(5) {
        ["id"]=>
        int(2)
        ["parentid"]=>
        int(1)
        ["route"]=>
        string(6) "parent"
        ["title"]=>
        string(6) "parent"
        ["pages"]=>
        array(1) {
          [0]=>
          array(4) {
            ["id"]=>
            int(3)
            ["parentid"]=>
            int(2)
            ["route"]=>
            string(5) "child"
            ["title"]=>
            string(5) "child"
          }
        }
      }
    }
  }
}

如果你不需要保留parentid、route、title这些字段,可以在赋值到$branch之前手动unset对应字段即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:45:03