PHP前端开发

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

百变鹏仔 3天前 #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":[]},    ],]