【问题标题】:PHP - How to get all children by Recursive?PHP - 如何通过递归获取所有孩子?
【发布时间】:2021-02-25 06:46:05
【问题描述】:

show()函数返回错误数据,为什么只有一个children

如何修改recursiveData函数

预期结果:

[
    {
        "id": 1,
        "title": "p1",
        "parentId": 0,
        "children": [
            {
                "id": 5,
                "title": "p1-child1",
                "parentId": 1,
                "children": [
                    {
                        "id": 13,
                        "title": "p5-child",
                        "parentId": 5,
                        "children": [
                            {
                                "id": 14,
                                "title": "p13-child",
                                "parentId": 13
                            }
                        ]
                    }
                ]
            },
            {
                "id": 6,
                "title": "p1-child2",
                "parentId": 1
            }
        ]
    },
    {
        "id": 2,
        "title": "p2",
        "parentId": 0,
        "children": [
            {
                "id": 9,
                "title": "p2-child1",
                "parentId": 2
            }
        ]
    }
]
public function show()
    {
        $data = $this->getData(0);
        $res = $this->recursiveData($data);
        echo json_encode($res);
    }

    public function recursiveData($data)
    {
        if (empty($data)) {
            return false;
        }

        $children = [];
        foreach ($data as $dk => $dv) {
            $children = $this->getData($dv['id']);
            $data[$dk]['children'] = $children;
            $this->recursiveData($children);
        }
        return $data;
    }

    /**
     * Get data from database.
     * @return array
     **/
    public function getData($parent_id)
    {
        $tmp  = [];
        $data = DB::select('select id,title from category where parent_id<99 and parent_id = ?', [$parent_id]);
        foreach ($data as $dk => $dv) {
            $tmp[] = [
                'id'       => $dv->id,
                'title'    => $dv->title,
                'parentId' => $parent_id,
            ];
        }
        return $tmp;
    }

【问题讨论】:

  • 给出一些数据作为一个最小的可重复的例子。
  • 当您执行递归 $this-&gt;recursiveData($children); 时,您不会对返回的数据执行任何操作。
  • 您是否可以随意更改 json 的结构,或者这是您处理的结构?

标签: php recursion


【解决方案1】:

recursiveData()

修改

$data[$dk]['children'] = $children;
$this->recursiveData($children);

$data[$dk]['children'] = $this->recursiveData($children);

【讨论】:

    猜你喜欢
    • 2022-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    相关资源
    最近更新 更多