<?php
function getTree($array)
{
$level = 0;
$tree = [];
$stack = [uniqid(1) => &$tree]; //why uniqid? Try do debug without that :p
foreach($array as $item)
{
if($item['level']>$level) //expand stack for new items
{
//if there are child elements, add last to stack:
$top = key($stack);
if(count($stack[$top]))
{
end($stack[$top]);
$stack[uniqid()] = &$stack[$top][key($stack[$top])];
}
//add ['children'] dim to top stack element
end($stack);
$top = key($stack);
$stack[$top]['children'] = [];
$stack[uniqid(1)] = &$stack[$top]['children'];
//add current item as a first child of top stack element
end($stack);
$top = key($stack);
$stack[$top][] = $item;
}
elseif($item['level']<$level) //pop stack items till corresponding level
{
while($item['level']<$level--)
{
//two times: one for last pointer, one for ['children'] dim
array_pop($stack);
array_pop($stack);
}
end($stack);
$stack[key($stack)][] = $item;
}
elseif($item['level']==$level) //add to current level
{
//just add since top stack element will be ['children'] dim
$stack[key($stack)][] = $item;
}
end($stack);
$level = $item['level'];
}
return $tree;
}
$array = [
['level'=>1, 'name' => 'Root #1'],
['level'=>1, 'name' => 'Root #2'],
['level'=>2, 'name' => 'subroot 2-1'],
['level'=>3, 'name' => '__subroot 2-1/1'],
['level'=>2, 'name' => 'subroot 2-2'],
['level'=>1, 'name' => 'Root #3']
];
echo('<pre>');
$result = getTree($array);
print_r($result);