0

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.

0

1 Answer 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
)
Sign up to request clarification or add additional context in comments.

5 Comments

That works great. One thing though, if I had a similar setup but wanted to subtract the values from eachother wouldnt I use a -= instead of the +=? If I do that now I get a negative number instead of the proper results. ex: with += I get 13410 with -= I get -13410
What do you mean by proper results? If I removed a number from zero I'd expect it to be negative...
well lets say one of them has value of 6500 and the other has a value of 500. If I += them it is now 7000. For some reason if I -= it shows -7000. I would expect 6000 since 6500-500=6000. Do I misunderstand what that code is actually doing?
No - your first example is adding both values together, the second is subtracting both values (the loop will perform the same operator every time) - how do you differentiate between which values need to be added or subtracted, and is having -500 as one of your values not acceptable? (6500 + -500 = 6000)
Ok, gotcha. Thanks for the code. It works great for the first question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.