How do I sum all the values of a PHP column

0

asked by anonymous 28.07.2016 / 00:18

1 answer

1

I had posted an answer but I saw that what you wanted was PHP .

  

I created the solution based on the @William Novak comment to use array_sum with array_map

For you to make the sum without having to use a loop you need to redeem the balances and play them in array . Then just use array_sum .

  <?php

   // este array foi obtido a partir seleção feita no banco de dados
   $saldo = array(0, 20, 30, 40);

   // vamos usar o array_sum para fazer a soma
   $total = array_sum($saldo);

  ?>

But if your array is a multidimensional array with other data you can do so without a loop:

  $usuario = array(

    // abaixo temos o id do usuario e o saldo de cada um
    array( "id" => 0, "saldo" => 20),
    array( "id" => 2, "saldo" => 30),
    array( "id" => 3, "saldo" => 40),
    array( "id" => 4, "saldo" => 60),

  );

   // vamos usar o array_sum para fazer a soma

$total = array_sum(array_map(function($item) { 

    return $item['saldo']; 

}, $usuario));


 echo $total;

?>
    
28.07.2016 / 20:45