gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 14:02:47 27 4
gpt4 key购买 nike

我想获取父类别的所有子类别和孙类别,直至任何级别。我的表结构是这样的。 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com