Home » Php » php – How to count a same data in JSON?

php – How to count a same data in JSON?

Posted by: admin February 25, 2020 Leave a comment

Questions:

JSON to count:

[{"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"}]

this is my code

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);
        });

How to add the same year for example

2018 is must 562 , not 80 , 64

sorry for my bad english ><

How to&Answers:

Since it tagged with PHP, below is the process:

1.Decode your json data through json_decode()

2.Iterate over this decode array.

3.Add values of jumlah based on thn by creating new array (using thn as index).

4.Re-index array through array_values().

5.Encode new array data through 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);

Output: https://3v4l.org/hZWUh

Note:- Do above at PHP end, and no need to change jQuery code. Thanks

Answer:

You can use reduce() to easily accomplish this:

// 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;
}, {});

This will set counts to:

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