php - 求算法帝,如何把个一个带有父子级关系的数组,怎么把它们组成一个带等级排序的数组
習慣沉默
習慣沉默 2017-05-31 10:34:56
0
2
1024
$data = [
            ['id' => 1,'pid' => 0,'name' => '销售部'],
            ['id' => 2,'pid' => 0,'name' => '技术部'],
            ['id' => 3,'pid' => 2,'name' => '前端'],
            ['id' => 4,'pid' => 1,'name' => '电话销售'],
            ['id' => 5,'pid' => 2,'name' => '后端'],
            ['id' => 6,'pid' => 1,'name' => '电商销售'],
            ['id' => 7,'pid' => 5,'name' => 'php'],
            ['id' => 8,'pid' => 7,'name' => 'php子部门'],
            ['id' => 9,'pid' => 6,'name' => '淘宝销售'],
            ['id' => 10,'pid' => 4,'name' => '打电话员'],
    ];

实现成:

$data = [
            ['id' => 1,'pid' => 0,'name' => '销售部','level' => 0],
            ['id' => 4,'pid' => 1,'name' => '电话销售','level' => 1],
            ['id' => 10,'pid' => 4,'name' => '打电话员','level' =>2],
            ['id' => 6,'pid' => 1,'name' => '电商销售','level' => 2],
            ['id' => 9,'pid' => 6,'name' => '淘宝销售','level' =>1],

            ['id' => 2,'pid' => 0,'name' => '技术部','level' => 0],
            ['id' => 3,'pid' => 2,'name' => '前端','level' => 1],
            ['id' => 5,'pid' => 2,'name' => '后端','level' => 1],
            ['id' => 7,'pid' => 5,'name' => 'php','level' => 2],
            ['id' => 8,'pid' => 7,'name' => 'php子部门','level' => 3],
    ];
習慣沉默
習慣沉默

全部回复(2)
大家讲道理

首先获取pid 为key 对应的数组关系对

>  $a1 =   pid[0] = [[id, pid=0, name],[id, pid=0, name]]
>          pid[1] = [[id, pid=1, name],[id, pid=1, name]]

       

写个递归函数

function buildArr(& $a, $start, $level) {
    foreach($a[$start] as $pid => $aa) {
        $a[$start][$pid]['level'] = $level;
        if(isset($a[$pid])) {
            buildArr($a, $pid, $level + 1);
        }
    }
}

调用:buildArr($a1, 0, 0);

再然后 循环获取$a1 内容就好了

迷茫

首先你要明确这里面不能有循环引用,比如说 id=0 pid=1和id=1 pid=0不能同时存在,然后你就可以建立一个多叉树的森林结构,最后怎么遍历每棵树,前中后序,层次遍历什么的,很easy吧

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板