I have a multidimensional array and I need to add up some of the data.
我有一个多维数组,我需要添加一些数据。
My array looks like this (there is a lot more data I cropped out for the example):
我的数组看起来像这样(我为这个例子裁剪了更多的数据):
Array
(
[0] => Array
(
[date] => 20-02-2014
[tool] => mystuff1
[usage] => 447
[minutes] => 6705
)
[1] => Array
(
[date] => 20-02-2014
[tool] => mystuff2
[usage] => 20
[minutes] => 1200
)
There will be more than one sub-array that has tool=mystuff1 and I want to add the "minutes" key up for all the ones that have mystuff1. Ultimately I want to do the same with mystuff2 added up (there are other 'tool' keys besides those that will be done as well.)
将有多个具有tool = mystuff1的子数组,并且我想为所有具有mystuff1的子项添加“分钟”键。最终我想对mystuff2加起来做同样的事情(除了那些将要完成的工具之外还有其他'工具'键。)
Ive tried several examples I found on this site but they all seem sum based on the 1 key name i.e. 'minutes' but not anything I can find where I can sum the 'minutes' when 'tool' also matches.
我已经尝试了几个我在这个网站上找到的例子,但它们看起来总是基于1个关键名称,即'分钟',但我找不到任何可以在“工具”匹配的时候总结“分钟”的地方。
1 个解决方案
#1
1
You can loop through your array and add the minutes value to the array key of an output array:
您可以循环遍历数组并将分钟值添加到输出数组的数组键:
$output = array();
foreach($your_array as $current) {
// create the array key if it doesn't exist already
if(!array_key_exists($current['tool'], $output))
$output[$current['tool']] = 0;
// add minutes to the current tool total
$output[$current['tool']] += $current['minutes'];
}
This way you can expect a result like this:
这样你可以得到这样的结果:
Array
(
[mystuff1] => 6705
[mystuff2] => 1200
)
#1
1
You can loop through your array and add the minutes value to the array key of an output array:
您可以循环遍历数组并将分钟值添加到输出数组的数组键:
$output = array();
foreach($your_array as $current) {
// create the array key if it doesn't exist already
if(!array_key_exists($current['tool'], $output))
$output[$current['tool']] = 0;
// add minutes to the current tool total
$output[$current['tool']] += $current['minutes'];
}
This way you can expect a result like this:
这样你可以得到这样的结果:
Array
(
[mystuff1] => 6705
[mystuff2] => 1200
)