【发布时间】:2012-07-19 21:29:58
【问题描述】:
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')在ratings表中)
现在用简单的英语:
我正在遍历 items 表中的每一行。当我这样做时,在每个循环中,我指的是另一个名为“评分”的表,并计算该项目有多少评分。
例如,我希望数组看起来像(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 输出: 数组([0] => 783 [items_id] => 783 [1] => 0 [rate] => 0)
【问题讨论】:
-
您应该考虑改用连接查询。
标签: php mysql arrays while-loop