本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

如何用PHP递归函数根据树状结构划分层级?

网络教程 app 1℃

如何用PHP递归函数根据树状结构划分层级

根据树状结构划分层级

在 php 中,我们可以使用递归来实现根据树状结构划分层级:

假定输入 $tree 数组如下:

[ {"id":1,"name":"人事","pid":0,"level":0,"son":[{"id":3,"name":"招聘部","pid":1,"level":1,"son":[{"id":7,"name":"研发部","pid":3,"level":2,"son":[]},{"id":8,"name":"行政部","pid":3,"level":2,"son":[]}]},{"id":4,"name":"人事部","pid":1,"level":1,"son":[]}]}, {"id":2,"name":"技术部","pid":0,"level":0,"son":[{"id":5,"name":"研发部","pid":2,"level":1,"son":[]},{"id":6,"name":"运维部","pid":2,"level":1,"son":[]}]}]

递归函数:

function groupbylevel($tree) { $result = []; foreach ($tree as $node) { $result[$node[‘level’]][] = $node; if (!empty($node[‘son’])) {$result = array_merge($result, groupbylevel($node[‘son’])); } } return $result;}

执行该函数:

$result = groupbylevel($tree);

输出结果:

[ 0 => [ {"id":1,"name":"人事","pid":0,"level":0,"son":[…]}, {"id":2,"name":"技术部","pid":0,"level":0,"son":[…]}, ], 1 => [ {"id":3,"name":"招聘部","pid":1,"level":1,"son":[…]}, {"id":4,"name":"人事部","pid":1,"level":1,"son":[…]}, {"id":5,"name":"研发部","pid":2,"level":1,"son":[…]}, {"id":6,"name":"运维部","pid":2,"level":1,"son":[…]}, ], => [ {"id":7,"name":"研发部","pid":3,"level":2,"son":[]}, {"id":8,"name":"行政部","pid":3,"level":2,"son":[]}, ],]

以上就是如何用PHP递归函数根据树状结构划分层级?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » 如何用PHP递归函数根据树状结构划分层级?

喜欢 (0)