将 3d 数组转换为唯一值的关联数组并对它们的相关值求和
我需要展平多维数组以形成唯一值及其总和的关联数组。
我的示例数组:
[
[
'winners' => [
'Gold Member',
'CROTCH SNIFFER',
'TEAM #1'
],
'prizeTotal' => 20
],
[
'winners' => [
'TEAM #1',
'CROTCH SNIFFER'
],
'prizeTotal' => 60
],
[
'winners' => [
'Gold Member',
'TEAM #1'
],
'prizeTotal' => 30
],
[
'winners' => [
'TEAM #1',
'TEAM #2',
'SCREW-NUT-BOLT'
],
'prizeTotal' => 90
]
]
请原谅这些名字...这不是我的数据库。
在每个数据集中,prizeTotal
被授予获胜者
中的每个值代码>子数组。
如何对 winners
值进行分组并对它们各自的 prizeTotal
值进行求和?
期望的结果:
array (
'Gold Member' => 50,
'CROTCH SNIFFER' => 80,
'TEAM #1' => 200,
'TEAM #2' => 90,
'SCREW-NUT-BOLT' => 90,
)
I need to flatten a multidimensional array to form an associative array of unique values and their sums.
My sample array:
[
[
'winners' => [
'Gold Member',
'CROTCH SNIFFER',
'TEAM #1'
],
'prizeTotal' => 20
],
[
'winners' => [
'TEAM #1',
'CROTCH SNIFFER'
],
'prizeTotal' => 60
],
[
'winners' => [
'Gold Member',
'TEAM #1'
],
'prizeTotal' => 30
],
[
'winners' => [
'TEAM #1',
'TEAM #2',
'SCREW-NUT-BOLT'
],
'prizeTotal' => 90
]
]
Please forgive the names...it's not my DB.
In each data set, the prizeTotal
is awarded to each value in the winners
subarray.
How can I group the winners
values and sum their respective prizeTotal
values?
Desired result:
array (
'Gold Member' => 50,
'CROTCH SNIFFER' => 80,
'TEAM #1' => 200,
'TEAM #2' => 90,
'SCREW-NUT-BOLT' => 90,
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要创建一个新数组来保存您的结果,然后对于每个现有数组,检查您是否已经为该团队处理了一个数组。
如果有,则只需将prizeTotal添加到存储在新数组条目中的prizeTotal即可那个团队。
如果没有,只需将团队的条目添加到新数组中即可。
You need to make a new array to hold your results, then for each of your existing arrays, check if you're already processed one for that team
If you have, then simply add the prizeTotal to the prizeTotal stored in your new array's entry for that team.
If not, simply add the team's entry to your new array.
要生成唯一团队及其累积得分的关联数组:
extract()
方便地访问作为单独变量的获胜者和prizeTotal 数据。代码:(演示)
“数组解构”可以代替调用
extract()
也创建单独的变量。To generate an associative array of unique teams and their cumulative scores:
extract()
to conveniently access the winner and prizeTotal data as individual variables.Code: (Demo)
Instead of calling
extract()
, "array destructuring" can create individual variables as well.我制作了一个模仿 mysql
SUM()
和GROUP BY
的函数。我希望它能满足您的需求:结果:
I have made a function that imitates mysql
SUM()
andGROUP BY
. I hope it will fit your needs:the result:
假设您可以将所有数组收集到一个 ie 中:
那么
这应该会产生如下结果:
Assuming you can collect all your arrays into one i.e. :
then
this should produce something like: