为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 JSON 中计算相同的数据?

如何在 JSON 中计算相同的数据?

PHP
慕码人2483693 2022-09-25 19:05:16
要计数的 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对不起我的英语不好><
查看完整描述

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}


查看完整回答
反对 回复 2022-09-25
?
烙印99

TA贡献1829条经验 获得超13个赞

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

1.通过以下方式解码您的 json 数据json_decode()

2.迭代此解码数组。

3.通过创建新数组(用作索引)添加基于的值。jumlahthnthn

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

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

注意:- 在PHP端执行上述操作,无需更改j查询代码。谢谢


查看完整回答
反对 回复 2022-09-25
  • 2 回答
  • 0 关注
  • 131 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号