alikhar2018
alikhar2018

Reputation: 145

Looping through an array and add up with same value of a key

This is the sample json encoded array-

[
    {"item_id":"8057","category":"MEN'S CLOTHING","quantity":"3.000"},
    {"item_id":"22647","category":"WOMEN'S CLOTHING","quantity":"7.000"},        
    {"item_id":"1556","category":"MEN'S CLOTHING","quantity":"2.000"},
    {"item_id":"4179","category":"WOMEN'S CLOTHING","quantity":"1.000"},
    {"item_id":"21218","category":"WOMEN'S CLOTHING","quantity":"2.000"}
]

I want to add up quantity with same category.

Need final result something like-

"MEN'S CLOTHING" : 5,
"WOMEN'S CLOTHING": 10

Note: the value of key 'category' is dynamic

Upvotes: 2

Views: 71

Answers (2)

akshaypjoshi
akshaypjoshi

Reputation: 1295

You can achieve this using below code:

    $json = json_decode($string,true);

    $allCount = [];
    foreach ($json as $key => $value){
        $allCount[$value['category']] += $value['quantity'];
    }
    foreach ($allCount as $category => $value){
        echo $category ." : ".$value."<br>";
    }

But When I run it in different PHP version through the console, it gives the warnings and displayed following result:

PHP Notice: Undefined index: MEN'S CLOTHING in /home/akshay/so.php on line 15 PHP Stack trace: PHP 1. {main}() /home/akshay/so.php:0

PHP Notice: Undefined index: WOMEN'S CLOTHING in /home/akshay/so.php on line 15 PHP Stack trace: PHP 1. {main}() /home/akshay/so.php:0

MEN'S CLOTHING : 5
WOMEN'S CLOTHING : 10

Upvotes: 0

Shail Paras
Shail Paras

Reputation: 1163

You can try something like that:

$dataArray = json_decode($jsonArray, true);
     $allValuesWithCount = array(); 
    foreach($dataArray as $arrayValues) {    
        $allValuesWithCount[$arrayValues['category']] += $arrayValues['quantity'];
     } 
    print_r($allValuesWithCount);

Upvotes: 1

Related Questions