How to sum array value of duplicate data

前端 未结 5 1390
滥情空心
滥情空心 2020-12-20 01:41

I have an array with some of same ID value as shown in below.

[
    {\"ID\":\"126871\",\"total\":\"200.00\",\"currency\":\"USD\",\"name\":\"John         


        
5条回答
  •  忘掉有多难
    2020-12-20 02:19

    You will need to:

    • Convert your json string to a php array with json_decode.
    • Loop through the rows and group them using compound temporary keys. In other words generate a single string from each row's ID & currency values and use that string as the temporary unique key.
    • Sum the grouped row's total values.
    • Then prepare the output array for its return to json by reindexing the rows and calling json_encode().

    Code: (Demo)

    $json='[
        {"ID":"126871","total":"200.00","currency":"USD","name":"John"},
        {"ID":"126872","total":"2000.00","currency":"Euro","name":"John"},
        {"ID":"126872","total":"1000.00","currency":"Euro","name":"John"},
        {"ID":"126872","total":"500.00","currency":"USD","name":"John"},
        {"ID":"126872","total":"1000.00","currency":"Euro","name":"John"}
    ]';
    
    $array=json_decode($json,true);  // convert to array
    foreach($array as $row){
        if(!isset($result[$row['ID'].$row['currency']])){
            $result[$row['ID'].$row['currency']]=$row;  // on first occurrence, store the full row
        }else{
            $result[$row['ID'].$row['currency']]['total']+=$row['total'];  // after first occurrence, add current total to stored total
        }
    }
    $result=json_encode(array_values($result));  // reindex the array and convert to json
    echo $result;  // display
    

    Output:

    [
        {"ID":"126871","total":"200.00","currency":"USD","name":"John"},
        {"ID":"126872","total":4000,"currency":"Euro","name":"John"},
        {"ID":"126872","total":"500.00","currency":"USD","name":"John"}
    ]
    

提交回复
热议问题