2 回答

TA贡献1943条经验 获得超7个赞
您可以使用 来轻松完成此操作:reduce()
// Your JSON data
let data = [{'thn': '2017', 'jumlah': '30'}, {'thn': '2018', 'jumlah': '80'}, {'thn': '2018', 'jumlah': '64'}, {'thn': '2018', 'jumlah': '5'}, {'thn': '2018', 'jumlah': '1'}, {'thn': '2018', 'jumlah': '1'}, {'thn': '2018', 'jumlah': '4'}, {'thn': '2018', 'jumlah': '5'}, {'thn': '2018', 'jumlah': '198'}, {'thn': '2018', 'jumlah': '2'}, {'thn': '2018', 'jumlah': '202'}, {'thn': '2019', 'jumlah': '31'}, {'thn': '2019', 'jumlah': '1'}];
let counts = data.reduce((acc, {thn, jumlah}) => {
if (!acc[thn]) {
acc[thn] = 0;
}
acc[thn] += parseInt(jumlah);
return acc;
}, {});
这将设置为:counts
{2017: 30, 2018: 562, 2019: 32}

TA贡献1829条经验 获得超13个赞
由于它用 标记,下面是过程:PHP
1.通过以下方式解码您的 json 数据json_decode()
2.迭代此解码数组。
3.通过创建新数组(用作索引)添加基于的值。jumlah
thn
thn
通过 4.Re 索引数组。array_values()
5.通过 对新数组数据进行编码。json_encode()
$array = json_decode($json,true);
$finalArray = array();
foreach($array as $arr){
$finalArray[$arr['thn']]['jumlah'] = (isset($finalArray[$arr['thn']]['jumlah']) ? $finalArray[$arr['thn']]['jumlah'] + $arr['jumlah']: $arr['jumlah']);
$finalArray[$arr['thn']]['thn'] = $arr['thn'];
}
$finalArray = array_values($finalArray);
echo json_encode($finalArray);
注意:- 在PHP端执行上述操作,无需更改j查询代码。谢谢
- 2 回答
- 0 关注
- 131 浏览
添加回答
举报