表格結構:
comment_id 評論ID
arc_id 文章ID
content 內容
parent_id 評論父節點
想要遞迴得到這樣的資料結構:
$arr=array(
[0]=>array(
comment_id=>1
parent_id =>0
['child']=>array(
[0]=>array(
comment_id=>2
parent_id =>1
)
[1]=>array(
comment_id=>3
parent_id =>2
)
[2]=>array(
comment_id=>4
parent_id =>1
)
........
)
)
[1]=>array(
comment_id=>5
parent_id =>0
['child']=>array(
[0]=>array(
comment_id=>6
parent_id =>5
)
[1]=>array(
comment_id=>7
parent_id =>5
)
[2]=>array(
comment_id=>8
parent_id =>7
)
........
)
)
)
欧阳克2017-06-30 09:55:28
先取出一個二維數組,其中每一項帶有comment_id
和parent_id
字段
接著使用下面的函數,將上面的二維陣列轉成樹狀結構:
<?php
$arr = [
['comment_id' => 1, 'parent_id' => 0],
['comment_id' => 2, 'parent_id' => 0],
['comment_id' => 3, 'parent_id' => 2],
['comment_id' => 4, 'parent_id' => 1],
['comment_id' => 5, 'parent_id' => 4],
['comment_id' => 6, 'parent_id' => 4],
];
function getTree($arr = []) {
$a = array_column($a, NULL, 'comment_id');
$tree = [];
foreach($a as $i => &$v) {
if(isset($items[$item['parent_id']])){
$items[$item['parent_id']]['children'][] = &$items[$item['comment_id']];
} else {
$tree[] = &$items[$item['id']];
}
}
return $tree;
}