Adding value from an array

0

I need to do the sum of values provided by an array. The array comes from a select in the database.

The array looks like this:

Array ( 
         [0] => Array ( [valorPagamento] => 12 ) 
         [1] => Array ( [valorPagamento] => 50 ) 
         [2] => Array ( [valorPagamento] => 10 ) 
)

I would like to add these values: 12,50,10

I've already used array_sum this way:

echo "soma: ".array_sum($total);

The variable $total that brings the array, however the result of always 0;

I've also tried this function:

$sum = 0;
        foreach($total as $key=>$value){
            $sum+= $value;
        }
    echo $sum;

Here, when I use the fetch function it shows only the first line, when I use fetchAll it shows the following error:

  

Unsupported operand types

My codes are these: file paymentAccountsData.php (just the function I'm using):

function soma(){
        try{
            $stmt = $this->pdo->prepare("SELECT valorPagamento FROM pagamentocontas");

            $stmt->execute();

            $consulta = $stmt->fetchAll(PDO::FETCH_ASSOC);

            return $consulta;

        }catch (PDOException $ex){
            echo "ERRO 02: {$ex->getMessage()}";
        }
    }

file soma.php:

<?php  
    require_once ("../DAO/pagamentoContasDAO.php");

    $dao =  new pagamentoContasDAO();
    $consulta = $dao->soma();


?>

file payment Accounts.php:

<?php

    require_once ("../Controller/soma.php");

    $sum = 0;
        foreach($consulta as $key=>$value){
            $sum+= $value;
        }
    echo $sum;

?>

Well, I hope you have understood my problem.

    
asked by anonymous 20.03.2016 / 21:00

2 answers

4

You have a multidimensional array, so array_sum does not work. Its function is almost correct, just add the key valorPagamento :

$sum = 0;
foreach ($total as $key => $value){
    $sum += $value['valorPagamento'];
}
echo $sum;
    
20.03.2016 / 21:08
1

I used this method a lot, today it has this:

 $total = array_sum ( array_column($itens, 'preco') );

Remembering that the function array_column () appeared in PHP 5.5

    
03.09.2017 / 21:19