php - 减少对象数组内的数组
问题描述
我有这个数组:
Collection {#319 ▼
#items: array:6 [▼
"Seccion 1 Pregunta 1" => array:3 [▼
"satisfactory" => 2
"unsatisfactory" => 0
"total" => 2
]
"Seccion 1 Pregunta 2" => array:3 [▼
"satisfactory" => 2
"unsatisfactory" => 0
"total" => 2
]
"Seccion 1 pregunta 3" => array:3 [▼
"satisfactory" => 0
"unsatisfactory" => 1
"total" => 1
]
"Seccion 2 pregunta 1" => array:3 [▼
"satisfactory" => 3
"unsatisfactory" => 0
"total" => 3
]
"Seccion 2 pregunta 2" => array:3 [▼
"satisfactory" => 1
"unsatisfactory" => 1
"total" => 2
]
"Commentarios seccion 2" => array:3 [▼
"satisfactory" => 0
"unsatisfactory" => 0
"total" => 0
]
]
}
我想得到所有满意、不满意和总值的总和。就像是:
Collection {#319 ▼
#items: array:3 [▼
"satisfactory" => 8
"unsatisfactory" => 2
"total" => 10
]
}
解决方案
如果您知道所需的密钥,只需执行以下操作:
[
'satisfactory' => $collection->sum('satisfactory'),
'unsatisfactory' => $collection->sum('unsatisfactory'),
'total' => $collection->sum('total')
]
如果您不确定键是什么,请对第一项的键进行循环以创建与上述类似的数组。如果您需要将其作为集合,只需执行以下操作:
$newCollection = collect( ... array from above ... );
推荐阅读
- javascript - Discord bot 在尝试播放链接后崩溃(Node.js)
- python - CNN - 检测手写表情:ValueError:无法将输入数组从形状 (26,26,3) 广播到形状 (26)
- angular - 拖动时如何保持行的大小?
- tensorflow - 在 Google Colab 中获取 AttributeError
- android - 如何做通过http协议连接的按钮?
- python - 一种计算另一个元素之间的元素数量并返回数组的方法
- regex - REGEXEXTRACT:value,text函数有必要吗?
- javascript - 我如何使用 Javascript 下载我编辑过的 DOM 的 HTML 文件,并在下载的文件中保留我所做的更改?
- php - 为什么 fgetcsv() 有时显然将“文件结尾”视为错误?
- javascript - 反应功能组件类型错误:无法读取未定义的属性“道具”