从子类别中查找子子类别的子项

时间:2014-11-03 07:58:52

标签: php recursion

我目前有一个代码段,对于每个类别,它会找到子类别:

   $categories = array_map(
        function($child)
        {
            $child['children'] =
                $this->getChildren(
                    $child['id'],
                    !empty($this->request->get['language_id']) ?
                        $this->request->get['language_id'] : 1
                );
            return $child;
        }, $categories);

getChildren()会递归地获得一个类别的孩子:

private function getChildren($parent_id, $language_id) {
    $this->load->model('official/category');

    $children = 
        $this->model_official_category->getCategoriesByParentId(
            $parent_id,
            $language_id
        );

    // For each child, find the children.
    foreach ($children as $child) {
        $child['children'] = $this->getChildren(
            $child['id'],
            $language_id
        );
    }

    return $children;
}

目前,在array_map()中使用我的lambda函数,只会检索子类别的子项,因此如果每个子类别都有自己的子子类别,则不会将其保存到子项中

我如何根据我们的子类别显示子子类别?

我想用我的代码做的是拿一个父,得到它的孩子,然后把每个孩子都当作父母,并递归地得到它的孩子,但是我的JSON输出没有反映出来。只有父母有孩子 - 孩子没有孩子(尽管我的数据库有孩子)。

1 个答案:

答案 0 :(得分:1)

问题是你的递归foreach循环将它检索到的子项分配给子数据的副本,而不是子数据本身。

要解决此问题,您可以使用引用子数据的foreach循环,如下所示:

foreach ($children as &$child) {

然而 ,由于与PHP more info if you're interested内部实现foreach的方式有关的多种原因,它会相当多相反,使用for循环可以提高内存效率,因为这样可以避免子数据的相当多的写时复制副本:

for ($i = 0; isset($children[$i]); $i++) {
    $children[$i]['children'] = $this->getChildren(
        $children[$i]['id'],
        $language_id
    );
}

这是一个使用对象而不是数组来表示子数据的地方可能是一个好主意,因为对象总是通过引用传递(种类),行为将更像您最初期望的那样。

相关问题