为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
繁花如伊 2019-03-09 16:54:19
這是查詢結果 這是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);
查看完整回答
反对 回复 2019-03-18
  • 1 回答
  • 0 关注
  • 378 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信