Skip to content

Instantly share code, notes, and snippets.

@fmtarif
Created March 15, 2017 16:37
Show Gist options
  • Select an option

  • Save fmtarif/a49ec37910f51f5940ae2c2a3108a3f2 to your computer and use it in GitHub Desktop.

Select an option

Save fmtarif/a49ec37910f51f5940ae2c2a3108a3f2 to your computer and use it in GitHub Desktop.
#php Recursive function that creates a parent children nested array of unlimited hierarchy
<?php
/**
* @param $elements format like following
* [
'id' => 1,
'name' => 'root1',
'parent_id' => 0
]
*/
function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment