我正在开展一个项目,我需要计算每个特定帖子的评论总数,并在逗号分隔的字符串中打印评论者ID。 以下是我如何获取评论者的ID并计算评论
$commenters=mysql_query("select session_id from comments where onid='theid'");
$noof_comments=mysql_num_rows($commenters); //counting the comments working good
$forprintingid=mysql_fetch_array($commenters);/* now I know this array stores all the
session ids of commenters and I can print them by using while loop but
here I do not want to use any loops ..*/
输出可能看起来像
total comments =$noof_comments // total comments=13
commenters id= // it should be like 1,2,3,4,5,6,
如果重复任何id,只需使用一次。 请帮我。我被困在这里可能是内爆了 功能可能会有所帮助,但我不知道究竟是多少...... :(
答案 0 :(得分:3)
您可以在GROUP_CONCAT
中查看MySQL
函数,而不是在PHP中完全执行此操作,它会根据需要提供逗号分隔的字段值。
SELECT GROUP_CONCAT(field_name) FROM table_name...
答案 1 :(得分:1)
$commenters=mysql_query("select session_id from comments where onid='theid'");
$noof_comments=mysql_num_rows($commenters); //counting the comments working good
while($row=mysql_fetch_array($commenters))
$forprintingid[]=$row[0];
echo implode(',', $forprintingid); //it shoul be like 1,2,3,4,5,6,
答案 2 :(得分:1)
$r = array(); while($x = mysql_fetch_assoc($commenters)) $r[] = $x; $forprintingid = implode(",",$x);
一行代码:) 编辑这仍然算作一行吗?
答案 3 :(得分:1)
无论你需要循环什么。此外,您只需要数字索引或关联数组。
您可以创建一个功能:
function mysql_fetch_all($result, $result_type = MYSQL_ASSOC) {
while($rows[] = mysql_fetch_array($result, $result_type)) {} return $rows;
}
然后在结果数组上使用implode()
:
$forprintingid = implode(',', mysql_fetch_all($commenters));