DB
Date Price qty
2012-10-21 $11 150
2012-10-22 $12 90
2012-10-22 $12 10
2012-10-23 $13 250
CODE
$result = mysqli_query($con, "SELECT * FROM table ORDER BY 'date'");
while ($row = mysqli_fetch_array($result)) {
$orders[] = array(
'Date' => $row['date'],
'price' => $row['price'],
'Quantity' => $row['qty']
);
}
我不需要获取重复日期,对于那些重复日期,需要获得平均price
和Qty
的总和,如下例所示:
示例
Date Price qty
2012-10-21 $11 150
2012-10-22 $12 100
2012-10-23 $13 250
我尝试使用Array-map
,但我失败了,真的很感激
答案 0 :(得分:2)
我建议使用GROUP BY
和相应的aggregation functions使用此查询将问题移至数据库:
SELECT `date`, AVG( `price` ), SUM( `qty`)
FROM `table`
GROUP BY `date`
ORDER BY `date`
一般来说,让MySQL做这样的工作比将数据首先传输到应用程序并在那里重新安排更为明智。
答案 1 :(得分:0)
更改您的查询
SELECT Date, AVG(Price), SUM(Qty) FROM table
GROUP BY Date
或者更改php以检查数组中的日期并计算平均值和总和
答案 2 :(得分:0)
你能试试吗,
$result = mysqli_query($con, "SELECT date, AVG(Price) as price, SUM(qty) FROM table GROUP BY date ORDER BY date");
while ($row = mysqli_fetch_array($result)) {
$orders[] = array(
'Date' => $row['date'],
'price' => $row['price'],
'Quantity' => $row['qty']
);
}