【问题标题】:How to count a same data in JSON?如何在 JSON 中计算相同的数据?
【发布时间】:2020-02-18 04:59:41
【问题描述】:

要计数的 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

对不起我的英语不好>

【问题讨论】:

  • 欢迎来到 SO。请转至stackoverflow.com/help/how-to-ask
  • 这是什么逻辑?? 2018 is must 562 , not 80 , 64解释
  • @AbdullaNilam 在那个 json 数据中,2018 年的结果太多了,比如 2018 年是 80,而另一个 2018 年是 64,我想将它们添加到一年中 >

标签: php jquery json codeigniter


【解决方案1】:

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

【讨论】:

  • 数据是我的 json 数据,但我得到的数据来自 Welcome/checkData,结果就像我之前写的一样,我仍然不知道我必须把你的代码放在哪里>..
【解决方案2】:

由于标记为PHP,以下是流程:

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

2.迭代这个解码数组。

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

4.通过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 端执行上述操作,无需更改 jQuery 代码。谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多