首页 > 解决方案 > 循环遍历数组并添加相同的键值

问题描述

这是示例 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

注意:key 'category' 的值是动态的

标签: phparrays

解决方案


你可以尝试这样的事情:

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

推荐阅读