php - I want to ask you, Algorithm Emperor, how to combine an array with a parent-child relationship and how to combine them into a hierarchically sorted array.
習慣沉默
習慣沉默 2017-05-31 10:34:56
0
2
1029
$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' => '打电话员'],
    ];

Achieved as:

$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],
    ];
習慣沉默
習慣沉默

reply all(2)
大家讲道理

First get the array relationship pair corresponding to pid as key

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

       

Write a recursive function

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);
        }
    }
}

Call: buildArr($a1, 0, 0);

Then loop to get the content of $a1

迷茫

First of all, you have to make it clear that there cannot be circular references. For example, id=0 pid=1 and id=1 pid=0 cannot exist at the same time. Then you can build a multi-tree forest structure and finally how to traverse each tree. , front, middle, back order, level traversal, etc., it’s very easy

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template