我想让父类别的所有子孙类别达到任何级别。我的表结构是这样的。
任何人都可以建议我如何获得所有儿童类别(即手机类别的三星和S3)。
答案 0 :(得分:5)
你需要递归。创建这样的函数(假设您使用活动记录):
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
,catalog\model\catalog\category.php
下的{{1}}。
答案 1 :(得分:1)
假设你在数组中有这些,你需要使用递归循环。
// Information from database loaded into array
$array = array(
0 => array(
'category_id' => 12,
'category_name' => 'Phone',
'category_alias' => 'phone',
'parent_category' => 0
),
// ... other rows
);
$children = array(); // Will contain all our children and grandchildren
function FindChildrenAndGrandchildren(array $array, $parentId, $level = 0) {
$children = array();
foreach($array as $category) {
if($category['parent_category'] == $parentId) {
if($level == 0) {
$temp = FindChildrenAndGrandchildren($array, $category['category_id'], 1);
$category['children'] = $temp;
}
$children[] = $category;
}
}
return $children;
}
$children = FindChildrenAndGrandchildren($array, 12); // Start search