2011-06-21 24 views
0
得到螺紋/嵌套評論

我有一個MySQL表中的數據,(被稱爲信息),像這樣:試圖在PHP

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

(ID是自動遞增)

我想顯示此在PHP中的數據,這樣的:

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

我已嘗試不同的方法,但我似乎無法能夠讓他們的工作無論哪種方式。我知道我需要一個遞歸函數,但我該怎麼做呢?一個簡單的指針就足夠了;謝謝。

回答

0

以及你所得到的表:

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

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

迭代