开发者

Trying to get threaded/nested comments in PHP

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 point开发者_运维技巧er would be enough; thanks.


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']})"
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜