遍历数组,并添加与键相同的值

时间:2018-11-21 05:04:57

标签: php arrays

这是示例json编码的数组-

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

我想将quantity与相同的category加起来。

需要最终结果,例如-

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

注意:键“类别”的值是动态的

2 个答案:

答案 0 :(得分:1)

您可以尝试类似的操作:

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

答案 1 :(得分:0)

您可以使用以下代码实现此目的:

    $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>";
    }

但是当我通过控制台在不同的PHP版本中运行它时,它会给出警告并显示以下结果:

  

PHP注意:未定义的索引:第15行的/home/akshay/so.php中的男装   PHP堆栈跟踪:   PHP 1. {main}()/home/akshay/so.php:0

     

PHP注意:未定义的索引:第15行/home/akshay/so.php中的女装   PHP堆栈跟踪:   PHP 1. {main}()/home/akshay/so.php:0

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