0

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

_______________________
编号 | 正文 | 家长 |
1 | 一个 | 空 |
2 | 乙 | 1 |
3 | c | 1 |
4 | d | 2 |
----------------------

(id 是自动递增的)

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

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

我尝试了不同的方法,但我似乎无法让它们以任何一种方式工作。我知道我需要一个递归函数,但我该怎么做呢?一个简单的指针就足够了;谢谢。

4

1 回答 1

0

好吧,当你拿到桌子时:

$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']})"
   }
}
于 2011-06-21T19:11:43.213 回答