rjcode rjcode - 6 months ago 21
JSON Question

Get sum of values which have same value for key php array

I have below array,

Array ( [0] => Array ( [report_id] => 1 [amount] => 100.00 [category_name] => Trial1 ) [1] => Array ( [report_id] => 1 [amount] => 150.00 [category_name] => Trial2 ) [2] => Array ( [report_id] => 1 [amount] => 200.00 [category_name] => Trial2 )


What i want to send to have JSON with below format

It will get some of Equal category name and then send it as json.

[{'category_name': 'Trial1', 'Sum':100]}, {'category_name':'Trial2', 'Sum':350]


How can i achieve this?
Was thinking to get
foreach
loop and then make compare of category_name and use .=+ to get sum? but i lost there,

Thanks,

Answer

Try below solution:

<?php
$array = array ( 
'0' => Array ( 'report_id' => 1, 'amount' => '100.00', 'category_name' => 'Trial1' ) ,
'1' => Array ( 'report_id' => 1, 'amount' => '150.00' ,'category_name' => 'Trial2' ),
'2' => Array ( 'report_id' => 1, 'amount' => '200.00' ,'category_name' => 'Trial2' ) ,
);

$new_array = array();
foreach($array as $a){
    if(!isset($new_array[$a['category_name']]['amount'])){
        $new_array[$a['category_name']]['amount'] = 0;
    }
    $new_array[$a['category_name']] = array(
        'category_name' => $a['category_name'],
        'amount' => $new_array[$a['category_name']]['amount'] + $a['amount'],
    );
}

//print_r(array_values($new_array));

echo json_encode(array_values($new_array));

Output

[{"category_name":"Trial1","amount":100},{"category_name":"Trial2","amount":350}]