這是查詢結果
這是php查詢代碼
SELECT
FROM_UNIXTIME(add_time, '%Y-%m-%d') as add_time,
count(view_id) as viewTime
FROM `view`
GROUP BY `add_time`
這是整個php代碼
header('Content-type: application/json');
$chartData = $pdo->query(
"SELECT
FROM_UNIXTIME(add_time, '%Y-%m-%d') as add_time,
count(view_id) as viewTime
FROM `view`
GROUP BY `add_time` "
);
$data = array();
$key = 0;
foreach ($chartData as $item){
$data[$key] = array(
'date' => $item['add_time'],
'number' => $item['viewTime']
);
$key++;
}
echo json_encode($data);
打印結果
[{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"},{"date":"2018-08-16","number":"1"}.............
右邊的 viewTime 都是一筆數據但我想實現的是日期重複只要顯示一個但是同一個日期的數字都相加這能怎麼實現?我要在後端打印出這樣的json 可以的話附帶一下原理 感謝大神
1 回答
万千封印
TA贡献1891条经验 获得超3个赞
$data = array();
foreach ($chartData as $item) {
if (isset($data[$item['add_time']])) {
$data[$item['add_time']]['number'] += $item['viewTime'];
} else {
$data[$item['add_time']] = array(
'date' => $item['add_time'],
'number' => $item['viewTime']
);
}
}
$data = array_values($data);
echo json_encode($data);
- 1 回答
- 0 关注
- 378 浏览
添加回答
举报
0/150
提交
取消