Reputation: 97
I have this sql table
How to return it with php like?
Root1
- SubCat 1
-- SubSubCat 1
- SubCat 2
Root2
I found this, but i cant return it in form, that i need. But the script still displays all categories, first as a sub, and then as root.
How to make it?
Upvotes: 0
Views: 3540
Reputation: 1664
This does the job:
$items = array(
(object) array('id' => 42, 'sub_id' => 1),
(object) array('id' => 43, 'sub_id' => 42),
(object) array('id' => 1, 'sub_id' => 0),
);
$childs = array();
foreach($items as $item)
$childs[$item->sub_id][] = $item;
foreach($items as $item) if (isset($childs[$item->id]))
$item->childs = $childs[$item->id];
$tree = $childs[0];
print_r($tree);
This works by first indexing categories by parent_id. Then for each category, we just have to set category->childs to childs[category->id], and the tree is built !
So, now $tree is the categories tree. It contains an array of items with sub_id=0, which themselves contain an array of their childs, which themselves ...
Output of print_r($tree):
stdClass Object
(
[id] => 1
[sub_id] => 0
[childs] => Array
(
[0] => stdClass Object
(
[id] => 42
[sub_id] => 1
[childs] => Array
(
[0] => stdClass Object
(
[id] => 43
[sub_id] => 42
)
)
)
)
)
So here is the final function:
function buildTree($items) {
$childs = array();
foreach($items as $item)
$childs[$item->sub_id][] = $item;
foreach($items as $item) if (isset($childs[$item->id]))
$item->childs = $childs[$item->id];
return $childs[0];
}
$tree = buildTree($items);
Upvotes: 1