将二维数组的行按一列分组,并对每组内的另一列求和
我已经四处寻找,但我已经束手无策,所以我会让这件事变得简单。这就是我在 print_r 中所拥有的:
[
['name' => 'client interaction', 'y' => 2.7],
['name' => 'client interaction', 'y' => 0.1],
['name' => 'project planning', 'y' => 0.1],
['name' => 'client interaction', 'y' => 5.9],
]
这就是我想要的:
[
['name' => 'client interaction', 'y' => 8.7],
['name' => 'project planning', 'y' => 0.1]
]
I have searched around and I am at my wits end so I will make this easy. This is what I have in a print_r:
[
['name' => 'client interaction', 'y' => 2.7],
['name' => 'client interaction', 'y' => 0.1],
['name' => 'project planning', 'y' => 0.1],
['name' => 'client interaction', 'y' => 5.9],
]
And this is what I want it to be:
[
['name' => 'client interaction', 'y' => 8.7],
['name' => 'project planning', 'y' => 0.1]
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您想要的数组是否绝对有必要使用数字索引?如果我要这样做,我会这样做(尽管与您想要的数组不同)
这将为您提供一个具有以下结构的数组:
要取回键,您只需使用
foreach< 的第二种形式/code>循环
$name
将包含原始数组中的name
和$y
y
。Is it absolutely necessary that your desired array use numeric indeces? If I were to do this I would do it this way (not the same as your desired array though)
This will give you an array of this structure:
To get the keys back you simply use the second form of the
foreach
loop$name
will contain thename
and$y
they
in your original array.最后一个循环只是将
$hash
转换为您指定的确切格式。说明:
是一个临时结构,用于计算每个唯一名称的总和。
这将遍历您的原始数组 ($sourceArray) 并提取每个元素。
初始化一个变量来存储属于该名称的当前总和。
检查给定名称的值是否已存储在
$hash
中。将 $y 设置为先前为给定名称计算的总和(如果有的话)。
将给定名称的总和存储到我们的临时结构
$hash
中。将 $hash 转换为您想要的格式。
$result[] = ...
中的 empy [] 将表达式的右侧添加到$result
数组的末尾。The last loop is just to get
$hash
into the exact format you specified.Explanation:
Is a temporary structure used to compute the sums for each unique name.
This goes through your original array ($sourceArray) and pulls out each element.
Initializes a variable to store the current sum that belongs with that name.
Checks to see if a value has already been stored in
$hash
for the given name.Sets $y to the previously calculated sum for the given name, if there was one.
Stores the sum for the given name into our temporary structure
$hash
.converts $hash to the format you desired.
The empy []'s in
$result[] = ...
add the right hand side of the expression to the end of the$result
array.http://codepad.org/EjdHxgvt
http://codepad.org/EjdHxgvt