重写JSON字符串 - 由分组值键到一个新的数组? [英] Rewriting a JSON string - grouping keys by value into a new array?
问题描述
好吧,我有一个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"
}...
和我运行上json_de code,得到一个数组,现在我想通过该数组来运行和计算共1个记录和汇总共2个记录每个日期...(和日期可以去无论什么范围)。什么是这样做的最快/ niftiest方式?
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?
通过在foreach每个键=> VAL杆,然后莫名其妙组日期键进入新数组中的一个新的密钥,并添加在里面的总数,让我得到这个为输出排序循环,在最末尾的JSON饲料,后json_en code,按日期排序:
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,
}...
我将如何群发整个阵列json_en code之前数组值这样?
how would I group the array values like that before sending the whole array to json_encode?
推荐答案
我觉得用 $总计
数组索引你的日期
将在这里工作(如果我理解正确的话)。如下图所示,其中 $数据的例子东西
是你的德codeD 关联JSON数组:
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'],
);
}
}
这篇关于重写JSON字符串 - 由分组值键到一个新的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!