前序遍历
function toHierarchy($collection)
{
// Trees mapped
$trees = array();
$l = 0;
if (count($collection) > 0) {
// Node Stack. Used to help building the hierarchy
$stack = array();
foreach ($collection as $node) {
$item = $node;
$item['children'] = array();
// Number of stack items
$l = count($stack);
// Check if we're dealing with different levels
while($l > 0 && $stack[$l - 1]['depth'] >= $item['depth']) {
array_pop($stack);
$l--;
}
// Stack is empty (we are inspecting the root)
if ($l == 0) {
// Assigning the root node
$i = count($trees);
$trees[$i] = $item;
$stack[] = & $trees[$i];
} else {
// Add node to parent
$i = count($stack[$l - 1]['children']);
$stack[$l - 1]['children'][$i] = $item;
$stack[] = & $stack[$l - 1]['children'][$i];
}
}
}
return $trees;
}
$arr = array(
array( 'name' => 'Joe Splogs', 'depth' => 1 ),
array( 'name' => 'ProSplogger', 'depth' => 1 ),
array( 'name' => 'Pinky Lyres', 'depth' => 2 ),
array( 'name' => 'Pseudologia fantastica', 'depth' => 3 ),
array( 'name' => 'Pseudologia fantasticaxx', 'depth' => 4 ),
array( 'name' => 'TextLinkBarry', 'depth' => 1 ),
array( 'name' => 'Foo bar Jones', 'depth' => 1 )
);
print_r(toHierarchy($arr));
result:
Array
(
[0] => Array
(
[name] => Joe Splogs
[depth] => 1
[children] => Array
(
)
)
[1] => Array
(
[name] => ProSplogger
[depth] => 1
[children] => Array
(
[0] => Array
(
[name] => Pinky Lyres
[depth] => 2
[children] => Array
(
[0] => Array
(
[name] => Pseudologia fantastica
[depth] => 3
[children] => Array
(
[0] => Array
(
[name] => Pseudologia fantasticaxx
[depth] => 4
[children] => Array
(
)
)
)
)
)
)
)
)
[2] => Array
(
[name] => TextLinkBarry
[depth] => 1
[children] => Array
(
)
)
[3] => Array
(
[name] => Foo bar Jones
[depth] => 1
[children] => Array
(
)
)
)