I'm trying to implement a category system on my website. The problem is that a category can have child.
So far, my table category
looks like that :
id, name, parent_id
So far, I made a loop, but it only works for 2 levels. Here is my code :
for($i=0;$i<count($data);$i++){
$tree[$data[$i]->name] = array();
for($j=0;$j<count($data);$j++){
if($data[$j]->parent_id == $data[$i]->id){
$tree[$data[$i]->name][] = $data[$j]->name;
}
}
}
It return me an array as it :
Array
(
[0] => Array
(
[1] => Cat1
[children] => Array
(
[12] => sub cat 1
[13] => sub cat 2
[14] => sub cat 3
)
)
[1] => Array
(
[2] => Cat2
)
[2] => Array
(
[3] => Cat3
)
)
How can I make it efficient and recursive to have something more like :
Array
(
[0] => Array
(
[1] => Cat1
[children] => Array
(
[12] => sub cat 1
[13] => sub cat 2
[14] => sub cat 3
[children] => Array
(
[1] => sub sub cat 1
)
)
)
[1] => Array
(
[2] => Cat2
)
[2] => Array
(
[3] => Cat3
)
)
Thanks for your help
EDIT
I'm working on Zend, and it return me the data
as it :
Zend_Db_Table_Rowset Object
(
[_data:protected] => Array
(
[0] => Array
(
[id] => 1
[name] => Cinema
[type] => category
[slug] => cinema
[parent_id] => -1
)
[1] => Array
(
[id] => 2
[name] => Horror
[type] => category
[slug] => horror
[parent_id] => 1
)