2011-06-21 2 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

さてあなたは、テーブルを取得している:この機能を使用して

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