Created
May 2, 2018 11:31
-
-
Save yarimadam/b1450b6e8650e568784e8c73074f113b to your computer and use it in GitHub Desktop.
build tree structure from flat array with parent IDs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$menu = [ | |
1 => ['id' => 1, 'parent' => null, 'name' => 'Root Menu 1'], | |
2 => ['id' => 2, 'parent' => 1, 'name' => 'Sub Menu 1 > 1'], | |
3 => ['id' => 3, 'parent' => 1, 'name' => 'Sub Menu 1 > 2'], | |
4 => ['id' => 4, 'parent' => 2, 'name' => 'Sub Menu 1 > 1 > 1'] | |
]; | |
function buildTree(&$menu) | |
{ | |
foreach ($menu as $menuItem) { | |
if (is_null($menuItem['parent'])) continue; | |
$parent = $menuItem['parent']; | |
$menu[$parent]['sub'][] = &$menuItem; | |
} | |
return $menu; | |
} | |
echo json_encode(buildTree($menu), JSON_PRETTY_PRINT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment