Link to home
Start Free TrialLog in
Avatar of DanielAttard
DanielAttardFlag for Canada

asked on

Sum values of multi-dimensional array in PHP

How would I calculate the sum of these two values inside this multi-dimensional array?

Array
(
    [Dec 01, 2013] => Array
        (
            [COM] => Array
                (
                    [C] => Array
                        (
                            [T] => 620.25
                            [U] => 24.75
                        )

                )

        )

)

Open in new window

Avatar of gplana
gplana
Flag of Spain image

if your array is on a variable called $a try this:

$sum = 0;
foreach($e1 in $a) {
   foreach($e2 in $e1){
      foreach($e3 in $e2){
         foreach($e4 in $e3){
            $sum += $e4;
         }
      }
   }
}
// here the $sum variable has the sum of the values.
ASKER CERTIFIED SOLUTION
Avatar of gplana
gplana
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The marqusG solution is easier than mine, however my solution works for any array with 4 dimensions (as the array of your example).

MarqusG solution will only work on this specific example (with these values) while my solution will work for any 4-dimension array.

Hope it helps. Regards.
Yes, it's true. Depending on your specific needs, one solution is better than the other: if you know  the array structure, the array keys and the exact position of the values you need to sum, my solution is more concise and less expensive in terms of resources since it doesn't require to loop through the whole array.

But if you need a more abstract and flexible routine, then gplana's solution is the one which fits you needs.

Reading the question, I have choosen the quicker solution. :)

Cheers
See also the examples on the PHP man page:
http://php.net/manual/en/function.array-sum.php
Avatar of DanielAttard

ASKER

Thanks to everyone for the comments.  I learned from all of them.