doublel83422 2012-12-15 21:33
浏览 49
已采纳

重写JSON字符串 - 按值将键分组到新数组中?

Ok, I have a JSON string:

[{
"Name": "Title 1",
"Count1": 556,
"Count2": 5,
"Date": "2012-12-05"
}, {
"Name": "Title 2",
"Count1": 10,
"Count2": 100,
"Date": "2012-12-05"
}, {
"Name": "Title 3",
"Count1": 798,
"Count2": 11,
"Date": "2012-12-04"
}...

and I run json_decode on that, get an array, and now I want to run through that array and calculate totals for Count1 and Count2 for each date... (and the dates can go on for whatever range). What's the fastest/niftiest way of doing that?

Sort of loop through each key => val par in a foreach, and then somehow group the date keys into a new key in a new array and add the totals in there, so that I'm getting this as an output, in JSON feed at the very end, after json_encode, sorted by date:

[{
"Date": "2012-12-05"
"TotalCount1": 566,
"TotalCount2": 105,
}, {
"Date": "2012-12-04"
"TotalCount1": 798,
"TotalCount2": 11,
}...

how would I group the array values like that before sending the whole array to json_encode?

  • 写回答

2条回答 默认 最新

  • douliexu5623 2012-12-15 21:45
    关注

    I think using a $totals array indexed on your date would work here (if I understand you correctly). Something like the example below where $data is your decoded associative JSON array:

    $totals = array();
    
    foreach ($data as $row) {
        if (isset($totals[$row['Date']]) ) {
    
            $totals[$row['Date']]['TotalCount1']
                = $totals[$row['Date']]['TotalCount1'] + $row['Count1'];
    
            $totals[$row['Date']]['TotalCount2']
                = $totals[$row['Date']]['TotalCount2'] + $row['Count2'];
    
        } else {
    
            $totals[$row['Date']] = array(
                 'Date' => $row['Date'],
                 'TotalCount1' => $row['Count1'],
                 'TotalCount2' => $row['Count2'],
            );
    
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题