php - How to recursively get all comments of an article? ? ?
phpcn_u1582
phpcn_u1582 2017-06-30 09:53:28
0
1
944

Table structure:
comment_id comment ID
arc_id article ID
content content
parent_id comment parent node

Want to get such a data structure recursively:

$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
         )   
        ........
    )
)

)

phpcn_u1582
phpcn_u1582

reply all(1)
学霸
  1. First take out a two-dimensional array, each item has comment_id and parent_id fields

  2. Then use the following function to convert the above two-dimensional array into a tree structure:

<?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;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template