Skip to content

Instantly share code, notes, and snippets.

@blackymetal
Created March 23, 2018 01:15
Show Gist options
  • Save blackymetal/23a834bb4de7c7764e80133cb03e3e5c to your computer and use it in GitHub Desktop.
Save blackymetal/23a834bb4de7c7764e80133cb03e3e5c to your computer and use it in GitHub Desktop.
Build tree from flat array
<?php
$elements = array(
array(
'id' => 1,
'parent_id' => null,
'info' => array('data' => '')
),
array(
'id' => 2,
'parent_id' => 1,
'info' => array('data' => '')
),
array(
'id' => 6,
'parent_id' => 1,
'info' => array('data' => '')
),
array(
'id' => 4,
'parent_id' => 6,
'info' => array('data' => '')
),
array(
'id' => 3,
'parent_id' => 2,
'info' => array('data' => '')
),
array(
'id' => 10,
'parent_id' => null,
'info' => array('data' => '')
),
array(
'id' => 11,
'parent_id' => 10,
'info' => array('data' => '')
)
);
$result = buildTree($elements);
print json_encode($result);
function buildTree(array &$elements, $parentId = null)
{
$branch = array();
foreach ($elements as &$element) {
if ($element['parent_id'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
unset($element);
}
}
return $branch;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment