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

时间:2012-12-15 21:33:59

标签: php arrays json

好的,我有一个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_encode之后的JSON feed中将其作为输出,按日期排序:

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

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

2 个答案:

答案 0 :(得分: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...

答案 1 :(得分:2)

我认为使用$totals索引的date数组可以在这里工作(如果我理解正确的话)。类似下面的示例,其中$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'],
        );

    }
}