Skip to content

Instantly share code, notes, and snippets.

@yarimadam
Created May 2, 2018 11:31
Show Gist options
  • Save yarimadam/b1450b6e8650e568784e8c73074f113b to your computer and use it in GitHub Desktop.
Save yarimadam/b1450b6e8650e568784e8c73074f113b to your computer and use it in GitHub Desktop.
build tree structure from flat array with parent IDs
<?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