php - 循环遍历数组并添加相同的键值
问题描述
这是示例 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' 的值是动态的
解决方案
你可以尝试这样的事情:
$dataArray = json_decode($jsonArray, true);
$allValuesWithCount = array();
foreach($dataArray as $arrayValues) {
$allValuesWithCount[$arrayValues['category']] += $arrayValues['quantity'];
}
print_r($allValuesWithCount);
推荐阅读
- javascript - GetUserMedia 如何分别控制麦克风和网络摄像头?
- vuex - Vuex 与 Sinon:如何监视商店调度
- c# - 无法在 Xamarin 表单中更改 CollectionView 内 Frame 的背景颜色
- c++ - 如何在 int64_t 中输入几个变量?
- python - 在文件夹内创建文件后 Pytest 无法正常工作
- c - 是否可以在c中的函数参数中有#ifdef,#endif?
- python - 根据数据框自动添加跟踪
- python - 类型错误:“datetime.date”和“str”实例之间不支持“>=”
- html - 如何根据悬停的链接显示 div?
- python - 返回转换后的数据框的类