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.