DanielAttard
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
)
)
)
)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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
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
http://php.net/manual/en/function.array-sum.php
ASKER
Thanks to everyone for the comments. I learned from all of them.
$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.