0
Good is so me in my users table, I have the balance column, how do I add the balance of all users, ie the balance of all records in the table with PHP?
Thank you.
0
Good is so me in my users table, I have the balance column, how do I add the balance of all users, ie the balance of all records in the table with PHP?
Thank you.
1
I had posted a reply but I saw that what you wanted was with PHP.
I created the solution based on @William Novak’s comment to use array_sum with array_map
For you to make the sum without using a loop you need to redeem the balances and play them on one array
. Then just use the 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 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;
?>
Browser other questions tagged php mysql
You are not signed in. Login or sign up in order to post.
Don’t think about doing that with the
SUM()
in query ? Anyway you can also assign a variable that will be auto-summing every time you go through the record. Something like$saldoTotal += $coluna['saldo'];
that within the loop used to build the table.– William Novak
I didn’t want to wear while. There’s no other way to do?
– Gonçalo
Since you have the data in an array, you can go through it using a function
array_map()
, but I guess you can’t escape from a loop.– William Novak
Could you give an example in reply? , Thank you.
– Gonçalo
How the table is structured and what data you want to add?
– Inkeliz
Sum all records in the balance column.
– Gonçalo
Opá, it’s in hand Ideone.
– William Novak
just use the
SUM()
inquery
– Andrei Coelho
only after I saw that what you wanted was with php
– Andrei Coelho