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 
$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。呜呼
#20。另一个回复
#30。
,你好可怕

4

1 回答 1

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
于 2013-07-20T22:23:25.300 回答