如何获取codeigniter中父类的所有子类和孙子类? [英] How to get all the child and grandchild categories of a parent category in codeigniter?

查看:262
本文介绍了如何获取codeigniter中父类的所有子类和孙子类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得父类别的所有子类别和孙子类别直到任何级别。我的表结构是这样的。

I want to get all the child and grandchild categories of a parent category upto any level. My table structure goes like this.

任何人建议我如何获得所有的孩子类别(即三星和S3的电话类别)。

Can anyone suggest me how to get all the child categories (i.e. Samsung and S3 of phone category).

推荐答案

您需要递归。创建这样的函数(假设你使用活动记录):

You need recursivity. Create a function like this (assuming you use active records):

function getCategoriesByParentId($category_id) {
    $category_data = array();

    $category_query = $this->db->query("SELECT * FROM categories WHERE parent_category = '" . (int)$category_id . "'");

    foreach ($category_query->result() as $category) {
        $category_data[] = array(
            'category_id' => $category->category_id,
            'category_name' => $category->category_name,
            'category_alias' => $category->category_alias,
            'parent_category' => $category->parent_category
        );

        $children = getCategoriesByParentId($category->category_id);

        if ($children) {
            $category_data = array_merge($children, $category_data);
        }           
    }

    return $category_data;
}

并像这样调用:

$all_categories = getCategoriesByParentId(0);

输出将如下所示:

Array
(
    [0] => Array
        (
            [category_id] => 14
            [category_name] => s3
            [category_alias] => s3
            [parent_category] => 13
        )

    [1] => Array
        (
            [category_id] => 13
            [category_name] => Samsung
            [category_alias] => samsung
            [parent_category] => 12
        )

    [2] => Array
        (
            [category_id] => 12
            [category_name] => Phone
            [category_alias] => phone
            [parent_category] => 0
        )

)

更多信息,这取自 OpenCart 1.5.4 ,类 ModelCatalogCategory code> catalogue \model\catalog\category.php 。

For more info, this was taken from OpenCart 1.5.4, class ModelCatalogCategory under catalog\model\catalog\category.php.

这篇关于如何获取codeigniter中父类的所有子类和孙子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆