尝试在PHP中获取线程化/嵌套注释

尝试在PHP中获取线程化/嵌套注释,php,threaded-comments,Php,Threaded Comments,我在MySQL表中有数据,称为info,如下所示: _______________________ id | text | parent | 1 | a | NULL | 2 | b | 1 | 3 | c | 1 | 4 | d | 2 | ----------------------- >a (ID 1) >>b(ID 2) >>>d (ID 4, parent 2) >>c (ID 3) id

我在MySQL表中有数据,称为info,如下所示:

_______________________ id | text | parent | 1 | a | NULL | 2 | b | 1 | 3 | c | 1 | 4 | d | 2 | ----------------------- >a (ID 1) >>b(ID 2) >>>d (ID 4, parent 2) >>c (ID 3) id是自动递增的

我想用PHP显示这些数据,如下所示:

_______________________ id | text | parent | 1 | a | NULL | 2 | b | 1 | 3 | c | 1 | 4 | d | 2 | ----------------------- >a (ID 1) >>b(ID 2) >>>d (ID 4, parent 2) >>c (ID 3)
我尝试过不同的方法,但我似乎无法让它们发挥作用。我知道我需要一个递归函数,但我该怎么做呢?一个简单的指针就足够了;谢谢。

既然您拿到了桌子:

$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']) 
    }
}
使用此函数进行迭代:

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