表结构:
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;
}