Trying to get threaded/nested comments in PHP

2019-08-26 03:11发布

问题:

I have data in a MySQL table, (called info), like this:

_______________________
id  |  text  | parent |
1   | a      | NULL   |
2   | b      | 1      |
3   | c      | 1      |
4   | d      | 2      |
-----------------------

(id is auto incrementing)

I want to display this data in PHP, like this:

>a (ID 1)
>>b(ID 2)
>>>d (ID 4, parent 2) 
>>c (ID 3)

I have attempted different methods, but I can't seem to be able to get them to work either way. I know I need a recursive function, but how would I do this? A simple pointer would be enough; thanks.

回答1:

Well as you are getting the table:

$parents = array();
$children = array();
while($row = ...){
    if($row['parent'] == null){
         $parents[] = array ('id' => $row['id'], 'text' => $row['text']) 
    }
    else{
         if(!isset($children[$row['parent']])) $children[$row['parent']] = array();
         $children[$row['parent']][] = array ('id' => $row['id'], 'text' => $row['text']) 
    }
}

Iterate using this function:

function displayChildren($array, $id, $char = ">"){
   foreach($array as $ch){
        if($ch['id']  == $id)
           echo "$char {$ch['text']} (ID {$ch['id']})"
   }
}