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}

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ù)組(用作索引)添加基于的值。jumlah
thn
thn
通過(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);
注意:- 在PHP端執(zhí)行上述操作,無(wú)需更改j查詢代碼。謝謝
- 2 回答
- 0 關(guān)注
- 118 瀏覽
添加回答
舉報(bào)