Reputation: 3928
I have the following output from the database and I want to build a menu with this data.
$output = [
['id_struct' => 1, 'title' => 'A', 'parent' => 0],
['id_struct' => 2, 'title' => 'B', 'parent' => 0],
['id_struct' => 3, 'title' => 'B1', 'parent' => 2],
['id_struct' => 4, 'title' => 'B2', 'parent' => 3],
['id_struct' => 5, 'title' => 'C', 'parent' => 0],
];
With this output I need to build another array like this:
array (size=3)
0 =>
array (size=1)
'title' => string 'A' (length=1)
1 =>
array (size=2)
'title' => string 'B' (length=1)
'children' =>
array (size=1)
0 =>
array (size=2)
'title' => string 'B1' (length=2)
'children' =>
array (size=1)
0 =>
array (size=1)
'title' => string 'BB1' (length=3)
2 =>
array (size=1)
'title' => string 'C' (length=1)
It needs to be this format so I can export to JSON.
What is the best way to achieve this? I've found many solutions but all of them are to export the menu to html using print/echo and that will not work here.
Upvotes: 1
Views: 156
Reputation: 8606
Try this:
function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent'] == $parentId) {
$children = buildTree($elements, $element['id_struct']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
$tree = buildTree($output);
echo "<pre>";
print_r( $tree );
echo "</pre>";
Hope this helps.
Upvotes: 2