繁体   English   中英

从子类别中找到子类别的孩子

[英]Finding the children of the sub-sub-category from a sub-category

我目前有一个代码段,其中每个类别都可以找到子类别:

   $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输出并不反映这一点。 只有父母有孩子-子女没有孩子(尽管我的数据库中有他们)。

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

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

foreach ($children as &$child) {

但是 ,由于与PHP内部如何实现foreach有关的多种原因(有关更多信息,请关注 ),因此使用for循环会大大提高内存效率,因为这将避免很多复制操作-子数据的写入副本:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM