gpt4 book ai didi

php - 如何使用递归函数嵌套对评论的回复

转载 作者:可可西里 更新时间:2023-10-31 23:17:43 24 4
gpt4 key购买 nike

所以,我在评论表中有一个“父”列,我这样称呼评论...

SELECT 
id,
parent_id,
member,
name,
email,
ip,
comment,
img,
date
FROM cs_comments
WHERE (row_id='$cmtid' AND page_type='$cmtt')
ORDER BY date

我这样调用这个函数...`

$comment_data = array();

while ($comments_array = $comments->fetch_object()) {
$comment_data[] = $comments_array;
}

echoComments($comment_data, $memberlevel);

我有一个打印评论的功能设置,但是如何打印回复?该功能在其内部。

如果我的问题不清楚,我可以添加更多信息。

最佳答案

首先,您应该考虑直接在 SQL 查询中使用用户输入数据而不对其进行清理,这是非常危险的,不推荐这样做!


2) 最好将 parent_id 的默认值设置为 0,我不确定 null 是否会得到相同的结果


3) 您可以在 mysql 查询中转义日期和名称列,它可能与 mysql 本地变量和函数冲突

<?php
//Code in view
$comments = getComments($cmtid,$page_type);
echoComments($comment);



//This method will take all Comments with their replies at once;
function getComments($cmtid,$page_type,$parent=0)
{
GLOBAL $mysqli;
$comments = $mysqli->query("SELECT `id`,parent_id,member,`name`,email,ip,`comment`,img,`date`
FROM cs_comments
WHERE (row_id='{$cmtid}' AND page_type='{$cmtt}' AND parent_id = {$parent})
ORDER BY date(format)");
$comment_data = array();
while($comments_array = $comments->fetch_object())
{
$comments_array->replies = $comments_array->parent_id ? getComments($cmtid,$page_type,$comments_array->parent_id) : array();
$comment_data[] = $comments_array;
}
return $comment_data;
}


//This method will print comment with replies
function echoComments($comment_data)
{
foreach ($comment_data as $comment):
echo '<div class="comment">
'.$comment->comment.'
<hr />
'.echoComments($comment->replies).'
</div>';
endforeach;
}

?>

您可以使用此样式表为嵌套回复提供一些缩进:

<style>
.comment{
background:#fff;
}
.comment .comment{
margin-left:5px;
background:#eee;
}
<style>

关于php - 如何使用递归函数嵌套对评论的回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35258311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com