Skip to content

Instantly share code, notes, and snippets.

@bitsmanent
Last active November 10, 2018 20:39
Show Gist options
  • Save bitsmanent/52cd82048cb68f0542b3 to your computer and use it in GitHub Desktop.
Save bitsmanent/52cd82048cb68f0542b3 to your computer and use it in GitHub Desktop.
Returns a hierachically nidified array from a linear one. Infinite levels of nesting.
function buildhier($items, $pk = 'parent_id', $ck = 'id', $subk = 'children') {
$map = array();
foreach($items as $k => &$item) {
$c = $item[$ck];
$map[$c] = &$item;
}
unset($item);
foreach($items as $item) {
$p = $item[$pk];
if(!$p)
continue;
$c = $item[$ck];
if(!isset($map[$p][$subk]))
$map[$p][$subk] = array();
$map[$p][$subk][$c] = $map[$c];
$map[$c]['__rm'] = 1;
$map[$c] = &$map[$p][$subk][$c];
}
foreach($items as $k => $item) {
if(@$item['__rm'])
unset($items[$k]);
}
return $items;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment