这需要一个非常基本的递归函数来将子/父对解析为树结构,另一个递归函数将其打印出来。只有一个函数就足够了,但为了清楚起见,这里有两个函数(组合函数可以在这个答案的末尾找到)。
首先初始化子/父对数组:
$tree = array(
'H' => 'G',
'F' => 'G',
'G' => 'D',
'E' => 'D',
'A' => 'E',
'B' => 'C',
'C' => 'E',
'D' => null
);
然后将该数组解析为层次树结构的函数:
function parseTree($tree, $root = null) {
$return = array();
# Traverse the tree and search for direct children of the root
foreach($tree as $child => $parent) {
# A direct child is found
if($parent == $root) {
# Remove item from tree (we don't need to traverse this again)
unset($tree[$child]);
# Append the child into result array and parse its children
$return[] = array(
'name' => $child,
'children' => parseTree($tree, $child)
);
}
}
return empty($return) ? null : $return;
}
以及一个遍历该树以打印无序列表的函数:
function printTree($tree) {
if(!is_null($tree) && count($tree) > 0) {
echo '
- ';
foreach($tree as $node) {
echo '
'.$node['name'];printTree($node['children']);
echo '
';}
echo '
';}
}
和实际用法:
$result = parseTree($tree);
printTree($result);
这里是$ result的内容:
Array(
[0] => Array(
[name] => D
[children] => Array(
[0] => Array(
[name] => G
[children] => Array(
[0] => Array(
[name] => H
[children] => NULL
)
[1] => Array(
[name] => F
[children] => NULL
)
)
)
[1] => Array(
[name] => E
[children] => Array(
[0] => Array(
[name] => A
[children] => NULL
)
[1] => Array(
[name] => C
[children] => Array(
[0] => Array(
[name] => B
[children] => NULL
)
)
)
)
)
)
)
)
如果你想要更多的效率,你可以将这些功能合并为一个,减少迭代的次数:
function parseAndPrintTree($root, $tree) {
$return = array();
if(!is_null($tree) && count($tree) > 0) {
echo '
- ';
foreach($tree as $child => $parent) {
if($parent == $root) {
unset($tree[$child]);
echo '
'.$child;parseAndPrintTree($child, $tree);
echo '
';}
}
echo '
';}
}
你只会在这样小的数据集上保存8次迭代,但在更大的集合上它可能会有所不同。