php 合并数组成父子关系,php – 将一系列父子关系转换为层次树?

这需要一个非常基本的递归函数来将子/父对解析为树结构,另一个递归函数将其打印出来。只有一个函数就足够了,但为了清楚起见,这里有两个函数(组合函数可以在这个答案的末尾找到)。

首先初始化子/父对数组:

$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次迭代,但在更大的集合上它可能会有所不同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值