我有以下MySQL表,我需要以正确的顺序输出结果。
id title parent_id display_order level
20 company NULL 0 0
25 contact NULL 1 0
26 sales NULL 2 0
21 about 20 0 1
22 team 20 1 1
23 services 20 2 1
24 apps 23 0 2
正确的顺序如下:
Company
about
team
services
apps
Contact
Sales
我不知道如何进行查询,该查询将按"级别"然后按"display_order"排序,但要确保子项遵循其父项。
我正在寻找一个 MySQL 答案,但如果您有关于如何使用 PHP 解析结果的建议,我也会考虑。
任何帮助将不胜感激!
我经常使用 php-function 来获取具有级别的数组类别
public function getCategoryTreeForParentId($parent_id = 0) {
$categories = array();
$this->db->from('categories');
$this->db->where('parent_id', $parent_id);
$result = $this->db->get()->result();
foreach ($result as $mainCategory) {
$category = array();
$category['id'] = $mainCategory->id;
$category['name'] = $mainCategory->name;
$category['parent_id'] = $mainCategory->parent_id;
$category['sub_categories'] = $this->getCategoryTreeForParentId($category['id']);
$categories[$mainCategory->id] = $category;
}
return $categories;
}
在 html 中回显时,可以依靠level
值对类别进行分类