分类表:
________________________________________________________________________
| id | parent_id | name
————————————————————————————————————————————————————————————————————————
| 1 | 0 | Root
| 2 | 1 | Sub category of root
| 3 | 0 | category 1
| 4 | 3 | sub category of category 1
| 5 | 4 | sub category of first sub category of category 1
————————————————————————————————————————————————————————————————————————
public function getCategoryTree($level = 0) {
$rows = $this->db
->select(‘id,parent_id,name’)
->where(‘parent_id’, $level)
->get(‘categories’)
->result();
if (count($rows) > 0) {
foreach ($rows as $row) {
$rows = $this->getCategoryTree($row->id);
}
}
//return $rows;
}
echo $rows;
// output will be show as string so i have to return this string in a variable
Root
—Sub category of root
category 1
—sub category of category 1
——sub category of first sub category of category 1
解决方法:
代码中最大的问题是你在foreach循环中覆盖$rows.
另外,使用递归解决方案,就像你已经去过的那样,跟踪从函数/方法的内部调用返回的内容非常重要.
protected function getCategoryTree($level = 0, $prefix = '') {
$rows = $this->db
->select('id,parent_id,name')
->where('parent_id', $level)
->order_by('id','asc')
->get('categories')
->result();
$category = '';
if (count($rows) > 0) {
foreach ($rows as $row) {
$category .= $prefix . $row->name . "\n";
// Append subcategories
$category .= $this->getCategoryTree($row->id, $prefix . '-');
}
}
return $category;
}
public function printCategoryTree() {
echo $this->getCategoryTree();
}