猿问

如何在 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


对不起我的英语不好><


慕码人2483693
浏览 141回答 2
2回答

杨__羊羊

您可以使用 来轻松完成此操作:reduce()// Your JSON datalet 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}) => {&nbsp; &nbsp; if (!acc[thn]) {&nbsp; &nbsp; &nbsp; &nbsp; acc[thn] = 0;&nbsp; &nbsp; }&nbsp; &nbsp; acc[thn] += parseInt(jumlah);&nbsp; &nbsp; return acc;}, {});这将设置为:counts{2017: 30, 2018: 562, 2019: 32}

烙印99

由于它用 标记,下面是过程:PHP1.通过以下方式解码您的 json 数据json_decode()2.迭代此解码数组。3.通过创建新数组(用作索引)添加基于的值。jumlahthnthn通过 4.Re 索引数组。array_values()5.通过 对新数组数据进行编码。json_encode()$array = json_decode($json,true);$finalArray = array();foreach($array as $arr){&nbsp; &nbsp; $finalArray[$arr['thn']]['jumlah'] = (isset($finalArray[$arr['thn']]['jumlah']) ? $finalArray[$arr['thn']]['jumlah'] + $arr['jumlah']: $arr['jumlah']);&nbsp; &nbsp; $finalArray[$arr['thn']]['thn'] = $arr['thn'];}$finalArray = array_values($finalArray);echo json_encode($finalArray);输出:https://3v4l.org/hZWUh注意:- 在PHP端执行上述操作,无需更改j查询代码。谢谢
随时随地看视频慕课网APP
我要回答