So I've been searching for a good way to implement nested categories in mysql and stumbled upon this article:
http://falsinsoft.blogspot.com/2013/01/tree-in-sql-database-nested-set-model.html
Now I'm struggling with generating the nested array. I need to generate an array that looks like this
Array
(
[0] => Array
(
[id] => 1,
[name] => Electronics
[children] => Array
(
[0] => Array
(
[id] => 2,
[name] => Televisions
[children] => Array (...)
)
)
)
[1] => Array
(
[id] => 5,
[name] => Another Parent category
[children] => Array
(
[0] => Array
(
[id] => 6,
[name] => Child category
[children] => Array (...)
)
)
)
)
There is already a solution to this problem here but the function doesn't work with multiple root categories. The other root categories simply get ignored.
function create_tree($results) {
$return = $results[0];
array_shift($results);
if ($return['lft'] + 1 == $return['rgt'])
$return['leaf'] = true;
else {
foreach ($results as $key => $result) {
if ($result['lft'] > $return['rgt'])
break;
if ($rgt > $result['lft'])
continue;
$return['children'][] = create_tree(array_values($results));
foreach ($results as $child_key => $child) {
if ($child['rgt'] < $result['rgt'])
unset($results[$child_key]);
}
$rgt = $result['rgt'];
unset($results[$key]);
}
}
unset($return['lft'],$return['rgt']);
return $return;
}
@user3508721
Array
(
[0] => Array
(
[id] => 1
[title] => ELECTRONICS
[description] =>
[lft] => 1
[rgt] => 20
[depth] => 0
)
[1] => Array
(
[id] => 2
[title] => TELEVISIONS
[description] =>
[lft] => 2
[rgt] => 9
[depth] => 1
)
[2] => Array
(
[id] => 3
[title] => TUBE
[description] =>
[lft] => 3
[rgt] => 4
[depth] => 2
)
[3] => Array
(
[id] => 4
[title] => LCD
[description] =>
[lft] => 5
[rgt] => 6
[depth] => 2
)
[4] => Array
(
[id] => 5
[title] => PLASMA
[description] =>
[lft] => 7
[rgt] => 8
[depth] => 2
)
[5] => Array
(
[id] => 12
[title] => Parent
[description] =>
[lft] => 21
[rgt] => 24
[depth] => 0
)
[6] => Array
(
[id] => 14
[title] => Child
[description] =>
[lft] => 22
[rgt] => 23
[depth] => 1
)
)