我的评论存储在数据库中,其中包含评论所在的帖子ID,评论ID,评论父ID,创建时间,内容等。现在我有了查询这将选择特定帖子的所有评论并循环显示每个评论。但是,我怎么能缩进'评论表明他们是另一个评论的孩子?
我目前的想法(有点伪代码)是:
get comments
for each comments as comment {
if comment has parent
margin += 16;
style = margin-left: margin
else
margin = 0
<div class="post" style="<?php echo $style; ?>">
...
</div>
}
但是,由于某些回复定位不正确,或者有时甚至不在父评论下定位,因此似乎无法正常工作。我在这里做错了吗,有更好的方法吗?
实际代码(非常难看):
<?php
$comments = $backend->getCommentsFromPost($post_id);
$level = 0;
$margin = 0;
foreach ($comments as $comment) {
$author = $backend->getUserById($comment['comment_author_id']);
$author_name = $author[0]['user_name'];
$author_id_62 = $backend->to62($author[0]['user_id']);
$when = $backend->getTimePosted($comment['comment_created']);
$comment_karma = 2;
$style = "";
if ($comment['comment_parent'] != NULL) {
$margin = $margin + 60;
$style = "style=\"margin-left: " . $margin . "px;\"";
}
else {
$margin = 0;
}
?>
<div <?php echo $style; ?> class="post">
<div class="row">
<div class="col-md-8">
<div class="comment">
<p class="comment-data">
<a href="profile.php?user=<?php echo $author_id_62;?>"><?php echo $author_name; ?></a> | <?php echo $comment_karma; ?> points | <?php echo $when; ?></p>
<?php echo $comment['comment_content']; ?>
<p class="comment-footer">
<a class='cbtn btn-primary' title='upvote' href='#'><span class='fa fa-arrow-up'></span></a>
<a class='cbtn btn-primary' title='downvote' href='#'><span class='fa fa-arrow-down'></span></a>
<?php
if ($backend->isLoggedIn()) {
$user_id = $_SESSION['user_id'];
$comment_id = $backend->to62($comment['comment_id']); ?>
<a class='cbtn btn-primary' title='post reply' href='comment-reply.php?comment=<?php echo $comment_id; ?>'><span class='fa fa-reply'></span></a>
<?php
if ($user_id == $author[0]['user_id'] || $backend->isUserNotPeasant($user_id)) {
?>
<a class='cbtn btn-danger' title='delete comment' href="delete-comment.php?id=<?php echo $comment_id; ?>"><span class='fa fa-trash-o'></span></a>
<?php
}
}
?>
</p>
</div>
</div>
</div>
</div>
<?php } ?>
干杯
答案 0 :(得分:2)
应该简单地说:
<style>
.post {margin-left: 0;}
.post div {margin-left: 16px;}
</style>
<div class="post">
POST HERE
<div>
reply
<div>
2nd reply
<div>
4th level
</div>
</div>
</div>
<div>
reply 2
</div>
</div>
<div class="post">
another post
</div>
答案 1 :(得分:0)
您可以根据需要在任意数量的 
前添加评论。每个级别一个似乎很好。跟踪评论的级别深度,您可以从查询中获取该级别深度,并将其转换为 
之前的数字。
答案 2 :(得分:0)
首先获取没有父级的评论,然后循环并获取子评论。这会解决我的问题。