2013-07-20 48 views
0

我怎麼能顯示父(引)消息,孩子(回覆)消息

Database structure: 
post_id 
comment_id 
message 
parent_id 


SQL data: 
post_id: 1 
comment_id: 10 
message: boohooo 
parent_id: 0 
------------------ 
post_id: 1 
comment_id: 20 
message: another reply 
parent_id: 0 
------------------ 
post_id: 1 
comment_id: 30 
messsage: you are scary 
parent_id: 10 

這裏是低於代碼(翻譯從MySQL結果PHP)白衣什麼我到目前爲止PHP:帶引號的評論回覆系統。我怎樣才能顯示父(引)消息,孩子(回覆)消息

<?php 
$first_comment = new stdClass; 
$first_comment->cid = '1'; 
$first_comment->message = 'this is the first message'; 
$first_comment->parent = '0'; 

$second_comment = new stdClass; 
$second_comment->cid = '20'; 
$second_comment->message = 'this is the second message'; 
$second_comment->parent = '0'; 

$third_comment = new stdClass; 
$third_comment->cid = '30'; 
$third_comment->message = 'this is a reply to the first message'; 
$third_comment->parent = '10'; 

$comments = array ($first_comment, $second_comment, $third_comment); 

//print_r($comments); 

foreach ($comments as $c) { 
echo "#". $c->cid . " ". $c->message . "\n\n"; 
} 
?> 

相同的代碼可與此PHP的沙盒網站是小提琴:http://ideone.com/fwHUwv

我希望它這樣的輸出:

評論:

#10。 boohooo
#20。 另一個答覆
#30。 boohooo
你是可怕的

+0

不能粘貼那些23行的代碼在這裏?但是,更重要的是,這有什麼問題? –

+0

我已更新問題:) –

回答

0
<?php 
$first_comment = new stdClass; 
$first_comment->cid = '1'; 
$first_comment->message = 'this is the first message'; 
$first_comment->parent = '0'; 

$second_comment = new stdClass; 
$second_comment->cid = '2'; 
$second_comment->message = 'this is the second message'; 
$second_comment->parent = '0'; 

$third_comment = new stdClass; 
$third_comment->cid = '3'; 
$third_comment->message = 'this is a reply to the first message'; 
$third_comment->parent = '1'; 

$comments = array ($first_comment, $second_comment, $third_comment); 

//print_r($comments); 

foreach ($comments as $c) { 
    if($c->parent != 0) { echo "#". $c->cid . " ". $comments[$c->parent-1]->message . "\n"; echo $c->message; } 
    else { 
     echo "#". $c->cid . " ". $c->message . "\n\n"; 
    } 
} 
?> 

輸出:

#1 this is the first message 

#2 this is the second message 

#3 this is the first message 
this is a reply to the first message 
+0

如果註釋ID(cid)不連續,這似乎不起作用。我收到了一個_PHP通知:未定義偏移量:9在...._ 請參閱: http://ideone.com/4l85ra –