total_stars这里是代码,它是我想要做的最好的解释:
$total_stars = array();
$query = "SELECT items_id FROM items";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$item_id = $row['items_id'];
$sql = "Select Count(item_id) FROM ratings WHERE item_id = '{$item_id}'";
$result = mysql_query($sql);
$total_stars[] = mysql_fetch_array($result);
}
// To see the output by entering the URL I want to print_r
print_r($total_stars);
// In the end, I am trying to JSON encode this and will later output in Java for Android
print(json_encode($total_stars));
(为了不混淆,items_id 在 items 表中,item_id(没有's')在 rating 表中)
现在用简单的英语:
我正在遍历项目表中的每一行。当我这样做时,在每个循环中,我指的是另一个名为“评级”的表,并计算该项目有多少评级。
例如,我希望数组看起来像(65、43、55、43 等)。当然是样本数。但每个都代表表中每个项目的评分总数。如何让 print__r 在循环中显示 SQL 语句的结果?
尝试使用联接的更新代码:
$query = "SELECT items_id FROM items";
$q = 'SELECT
items.items_id,
COUNT(ratings.item_id) AS rate
FROM `items`
LEFT JOIN ratings ON (ratings.item_id = items.items_id)
GROUP BY items_id';
$result = mysql_query($q);
while ($row = mysql_fetch_array($result)) {
$total_stars = mysql_fetch_array($result);
}
print_r($total_stars);
print_r 输出: Array ( [0] => 783 [items_id] => 783 [1] => 0 [rate] => 0 )