您的位置 首页 知识分享

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

根据树状结构划分层级 在 php 中,我们可以使用递归来实现根据树状结构划分层级: 假定输入 $tree 数组…

如何用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":[...]},     ],     2 => [         {"id":7,"name":"研发部","pid":3,"level":2,"son":[]},         {"id":8,"name":"行政部","pid":3,"level":2,"son":[]},     ], ]
登录后复制

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

本文来自网络,不代表甲倪知识立场,转载请注明出处:http://www.spjiani.cn/wp/5792.html

作者: nijia

发表评论

您的电子邮箱地址不会被公开。

联系我们

联系我们

0898-88881688

在线咨询: QQ交谈

邮箱: email@wangzhan.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部