0

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,

3 Answers 3

3

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}]
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Works as required
1

Possible solution:

$categoriesArray = array();

foreach ($yourArray as $arrayItem) {
   if (!isset($categoriesArray[$arrayItem['category_name']])) {
       $categoriesArray[$arrayItem['category_name']] = array(
           'category_name' => $arrayItem['category_name'],
           'sum' => 0
       );
   }

   $categoriesArray[$arrayItem['category_name']]['sum'] += $arrayItem['amount'];
}

$categoriesArray = json_encode(array_values($categoriesArray));

Comments

1

Assuming $input is your array and $output is the JSON string:

$categorysum = [];
array_walk($input, function($el) use (&$categorysum) {
    $categorysum += [$el['category_name'] => ['category_name' => $el['category_name'], 'Sum' => 0]];
    $categorysum[$el['category_name']]['Sum'] += $el['amount'];
});
$output = json_encode(array_values($categorysum));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.