$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],
];
First get the array relationship pair corresponding to pid as key
Write a recursive function
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