PHP:带引号的评论回复系统。如何向子(回复)消息显示父(引用)消息

标签 php mysql comments

如何向子(回复)消息显示父(引用)消息

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/

相关文章:

PHP 查询 join 获取评论回复

mysql - 获取MySQL索引上次使用时间?

mysql - 使用 cpanel 备份单个数据库的 cron 作业

MySQL 将查询值赋给变量

xcode - 有没有在 Xcode 中进行 block 注释的快捷方式?

c# - 方法最佳实践末尾的评论?

javascript - 通过ajax将关联PHP数组传递给javascript时保留其顺序

php - 使用 mysql 和 php 显示 ID 匹配的数据库的单个结果

php - 在 Ubuntu 上启动简单的 php 守护进程

php - Codeigniter 使用 CURDATE() 选择数据