function get_comment_count_for_events() {
$query = "SELECT event_token , COUNT(NULLIF(event_token, '')) AS counts FROM comment GROUP BY event_token ORDER BY counts DESC;";
$result = mysql_query($query);
$comment_count = array();
while ($row = mysql_fetch_array($query)) {
$comment_count = $row;
}
if (!$result) {
trigger_error('Invalid query: ' . mysql_error() . " in " . $query);
}
return $comment_count;
}
<小时/>
这是我的职责。
我从其他文件中使用它
foreach (get_comment_count_for_events() as $comment_count_event) {
echo $comment_count_event['tiken_event'];
echo $comment_count_event['count'];
}
但是在数据库中,当我测试查询时它可以工作: 结果: event_token - 计数
1 - 13
2 - 13
8 - 11
3 - 8
5 - 7
7 - 4
6 - 3
''- 0
最佳答案
更新您的代码,您将覆盖您的 $comment_count
变量。您需要使用数组来代替;
while ($row = mysql_fetch_array($result)) {
$comment_count[] = $row;
}
此外,在第二次迭代中,字段名称不正确。也更新它们;
foreach (get_comment_count_for_events() as $comment_count_event) {
echo $comment_count_event['event_token'];
echo $comment_count_event['counts'];
}
关于php - 无法将从 sql 查询获取的元素添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22660484/