Skip to content

Instantly share code, notes, and snippets.

@mgarciaebo
Last active August 27, 2015 17:32
Show Gist options
  • Save mgarciaebo/0ea1c57815430f8355c0 to your computer and use it in GitHub Desktop.
Save mgarciaebo/0ea1c57815430f8355c0 to your computer and use it in GitHub Desktop.
Función recursiva para construir menú en arreglo mutlidimensional
<?php
function buildTree(array $elements, $parentId = NULL) {
$branch = array();
foreach ($elements as $key => $element) {
if ($element['parent'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
$rows = array(
array('id'=>'user', 'label' => 'User', 'parent' => NULL),
array('id'=>'courses', 'label' => 'Courses', 'parent' => NULL),
array('id'=>'courses-import', 'label' => 'Courses Import', 'parent' => 'courses'),
);
echo '<pre>';
$tree = buildTree($rows);
print_r($tree);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment