第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何在 JSON 中計(jì)算相同的數(shù)據(jù)?

如何在 JSON 中計(jì)算相同的數(shù)據(jù)?

PHP
慕碼人2483693 2022-09-25 19:05:16
要計(jì)數(shù)的 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對(duì)不起我的英語(yǔ)不好><
查看完整描述

2 回答

?
楊__羊羊

TA貢獻(xiàn)1943條經(jīng)驗(yàn) 獲得超7個(gè)贊

您可以使用 來(lái)輕松完成此操作: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;

}, {});

這將設(shè)置為:counts


{2017: 30, 2018: 562, 2019: 32}


查看完整回答
反對(duì) 回復(fù) 2022-09-25
?
烙印99

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超13個(gè)贊

由于它用 標(biāo)記,下面是過(guò)程:PHP

1.通過(guò)以下方式解碼您的 json 數(shù)據(jù)json_decode()

2.迭代此解碼數(shù)組。

3.通過(guò)創(chuàng)建新數(shù)組(用作索引)添加基于的值。jumlahthnthn

通過(guò) 4.Re 索引數(shù)組。array_values()

5.通過(guò) 對(duì)新數(shù)組數(shù)據(jù)進(jìn)行編碼。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端執(zhí)行上述操作,無(wú)需更改j查詢代碼。謝謝


查看完整回答
反對(duì) 回復(fù) 2022-09-25
  • 2 回答
  • 0 關(guān)注
  • 118 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)