Add values of a two-dimensional array and throw your total PHP

1

There is a method (array_sum) in PHP that adds the values of a two-dimensional array without having to traverse the array, but in this case I need to traverse that array without using this method to display the values per array and its 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 shows me the total of both ('SUMA1', 'SUMA2') fixes, what I could not achieve is that I printed the sum per arrangement, that is:

El total de 'SUMA1' es 19
El total de 'SUMA2' es 9
    
asked by JDavid 13.05.2018 в 06:47
source

3 answers

2
<?php
    $total = 0;
    $numbers = ["SUMA1" => [8,5,1,5], "SUMA2" => [2,2,5]];


    $i = 0;
    foreach ($numbers as $value) {
        $arr = array_keys($numbers);//Puedes ignorar este paso, solo es para sacar las claves
        $parcial = 0;//Debes sacar el total por cada iteración y resetarlo al terminar
        foreach ($value as $valores) {    
         $parcial += $valores;
         $total += $valores;
        }
        echo 'El total de' . $arr[$i] . ' es ' . $parcial. '<br>';
        $i++;
    }
echo "el total es: ".$total;

?>

I put you there some comments that makes the couple of lines I added, greetings.

    
answered by 13.05.2018 / 07:13
source
1

You can continue using array_sum , as follows.

I'll give you an improved version, in case you're interested in having a general total too.

I also added comments to the code for clarity:

    $total=0;
    $tmp=0;
    $numbers = ["SUMA1" => [8,5,1,5], "SUMA2" => [2,2,5]];
    /*Los arrays se pueden diferenciar como clave/valor usando "as"*/
    foreach ($numbers as $k=>$v) {
        /*Si el valor actual es un array, significa que debemos sumar*/
        if (is_array($v)){
              /*Suma del array actual*/
              $tmp=array_sum($v);
              echo "La suma de $k es: $tmp".PHP_EOL;
              /*Lo agregamos a un total general, en caso de que interese*/
              $total+=$tmp;
        }
    }
echo "El total general es: $total";

The key is to read both components of the original array, ask if $v is an array and then apply array_sum if it is.

The result would be:

La suma de SUMA1 es: 19
La suma de SUMA2 es: 9
El total general es: 28
    
answered by 13.05.2018 в 07:18
0

Another option can be using array_map() along with array_sum() .

Example:

$numbers = ["SUMA1" => [8,5,1,5], "SUMA2" => [2,2,5]];

// Obtenemos las sumas de cada uno de los array 
$sumas = array_map('array_sum', $numbers);

// recorrer y mostrar las sumas 
foreach($sumas as $key => $value) {
    echo 'La suma de '. $key .' es '. $value; 
}
// obtener y mostrar la suma general
echo 'La suma total es '. array_sum($sumas);
    
answered by 13.05.2018 в 10:23