如何向子(回复)消息显示父(引用)消息
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。 嘘
你很可怕
最佳答案
<?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
关于PHP:带引号的评论回复系统。如何向子(回复)消息显示父(引用)消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17766543/