php - Build a nested array from a menu in database -
i have following output database , want build menu 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 output need build array 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 format can export json.
what best way achieve this? i've found many solutions of them export menu html using print/echo , not work here.
try this:
function buildtree(array $elements, $parentid = 0) { $branch = array(); foreach ($elements $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 helps.
Comments
Post a Comment