search

Home  >  Q&A  >  body text

php - How to recursively get all comments of an article? ? ?

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_u1582phpcn_u15822745 days ago989

reply all(1)I'll reply

  • 欧阳克

    欧阳克2017-06-30 09:55:28

    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;
    }

    reply
    0
  • Cancelreply