There is a method (array_sum) in PHP that adds the values of a two-dimensional array without having to go through the array, but in this case I need to go through that array without using this method to show the values by array and their total.
Axis:
$total = 0;
$numbers = ["SUMA1" => [8,5,1,5], "SUMA2" => [2,2,5]];
foreach ($numbers as $value) {
foreach ($value as $valores) {
$total += $valores;
}
}
echo "el total es: ".$total;
When doing the echo
it shows me the total of both arrays ('SUMA1', 'SUMA2')
, what I have not been able to achieve is that it prints the sum per array, that is:
El total de 'SUMA1' es 19
El total de 'SUMA2' es 9
I put some comments there that makes the couple of lines I added, greetings.
You can continue using
array_sum
, as follows.I put an improved version for you, in case you are interested in also having a grand total.
I've also added comments to the code for clarity:
The key is to read both components of the original array, ask if
$v
it's an array, and then applyarray_sum
if it is.The result would be:
Another option can be using
array_map()
together witharray_sum()
.Example: