$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],
];
大家讲道理2017-05-31 10:36:56
首先取得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 內容就好了
迷茫2017-05-31 10:36:56
首先你要明確這裡面不能有循環引用,比如說id=0 pid=1和id=1 pid=0不能同時存在,然後你就可以建立一個多叉樹的森林結構,最後怎麼遍歷每棵樹,前中後序,層次遍歷什麼的,很easy吧