如何將同一天的筆數相加?印成正確的json

這是查詢結果

https://img4.mukewang.com/5c8f3d010001ee7001720561.jpg

這是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
可以的話附帶一下原理 感謝大神

繁花如伊
浏览 379回答 1
1回答

万千封印

$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);
打开App,查看更多内容
随时随地看视频慕课网APP