如何在JSON中统计相同的数据



JSON计数:

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

这是我的代码

var data_nama=[];
var data_jumlah=[];
$.post("<?=base_url('Welcome/checkData')?>",
function(data){
var obj = JSON.parse(data);
$.each(obj,function(test,item){
data_nama.push(item.thn);
data_jumlah.push(item.jumlah);
});

如何添加同一年份,例如

2018是必须562,而不是80,64

抱歉我英语不好;

您可以使用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}

由于它标记了PHP,下面是过程:

1.通过json_decode()解码您的json数据

2.在此解码数组上进行迭代。

3.通过创建新的数组(使用thn作为索引(,在thn的基础上添加jumlah的值。

4.通过CCD_ 8重新索引阵列。

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);

输出:https://3v4l.org/hZWUh

注意:-在PHP端执行以上操作,无需更改jQuery代码。感谢

相关内容

  • 没有找到相关文章