I want to simply create a multilevel category hierarchy from mysql
Category table:
________________________________________________________________________
| 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
————————————————————————————————————————————————————————————————————————
php
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
The biggest problem in your code was that you were overwriting $rows
inside your foreach loop.
Additionally, with a recursive solution, like you've gone for, it's important to keep track of what's been returned from the inner calls to the function/method.
Also, I've added an order by, to make sure the root category appears first.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With