php - 如何在 codeigniter 中获取父类别的所有子类别和孙类别?

标签 php codeigniter parent-child categories

我想获取父类别的所有子类别和孙类别,直至任何级别。我的表结构是这样的。 enter image description here

谁能建议我如何获取所有子类别(即手机类别的三星和 S3)。

最佳答案

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

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.4catalog\model\catalog\category.php 下的 ModelCatalogCategory 类。

关于php - 如何在 codeigniter 中获取父类别的所有子类别和孙类别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23780349/

相关文章:

ssis - ssis 中的参数绑定(bind)

php - "Cannot execute queries while other unbuffered queries are active"循环错误

php - 如何验证值是否存在于redis的列表中?

php - 在 PHP 中将 Unicode 字符转换为文本不起作用

php - 我应该在 URL 中允许 "."吗?

java - 创建一个容纳对象的对象?

php - 如何在我的元素中绘制饼图

php - 将自定义字段添加到管理产品 在 WooCommerce 3.2+ 中批量编辑

mysql - 如何在 View 文件上使用 NOT IN 查询

c - 信号量无法正常工作