2024-11-30

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

如何用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":[]}]}
]
登录后复制

递归函数:

立即学习PHP免费学习笔记(深入)”;

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中文网其它相关文章!

https://www.php.cn/faq/1120436.html

发表回复

Your email address will not be published. Required fields are marked *