Jason
Jason

Reputation: 23

PHP Sum keys in multidimensional array that match another key

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.)

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.

Upvotes: 0

Views: 698

Answers (1)

scrowler
scrowler

Reputation: 24406

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
)

Upvotes: 1

Related Questions