【问题标题】:Rewriting a JSON string - grouping keys by value into a new array?重写 JSON 字符串 - 按值将键分组到新数组中?
【发布时间】:2012-12-03 12:02:04
【问题描述】:

好的,我有一个 JSON 字符串:

[{
"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"
}...

然后我在上面运行 json_decode,得到一个数组,现在我想遍历该数组并计算每个日期的 Count1 和 Count2 的总数......(并且日期可以在任何范围内继续)。最快/最好的方法是什么?

通过foreach中的每个键=> val par进行某种循环,然后以某种方式将日期键分组到新数组中的新键中,并将总数添加到那里,以便我将其作为输出,在最后的 JSON 提要中,在 json_encode 之后,按日期排序:

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

在将整个数组发送到 json_encode 之前,我如何对数组值进行分组?

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    我认为在您的date 上使用索引的$totals 数组在这里可以工作(如果我理解正确的话)。类似于下面的示例,其中 $data 是您的 decoded 关联 JSON 数组:

    $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'],
            );
    
        }
    }
    

    【讨论】:

    • 如果您正在解码为对象,请参阅下面的@MichaelBerkowski 的解决方案;)
    • 我喜欢那个......好吧,另一个答案也是如此,但这更适合我的需要。谢谢!
    • 你能不能也附和这个:stackoverflow.com/questions/14008236/…
    【解决方案2】:

    您需要创建一个以Date 为键的输出数组。从 JSON 循环遍历每个子数组(或对象,如果你有的话),测试日期键是否已经存在并添加到它,或者创建它。

    最后,在其上调用array_values() 以剥离Date 键并将其转换为纯数字索引数组,然后再将其编码回JSON。

    $output = array();
    foreach ($original_array as $obj) {
      // If the date key ($obj->Date) already exists in the array, add the counts...
      if (isset($output[$obj->Date])) {
        $output[$obj->Date]->Count1 += $obj->Count1;
        $output[$obj->Date]->Count2 += $obj->Count2;
      }
      // Otherwise just append this object onto the output array
      // For objects, this must be cloned, since it would be saved as a reference otherwise.
      else {
        $output[$obj->Date] = clone $obj;
      }
    }
    
    // Then strip off the Date keys from the array:
    // ready to call json_encode() on again...
    $output = array_values($output);
    

    以上假设您最初的 json_decode() 调用为数组元素而不是关联数组生成了 stdClass 对象。

    Here's a sample...

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多