Adding numbers from an array

Asked

Viewed 1,955 times

1

I’m using a loop to show all the answers in a respective column of my bd. But I need to add all the numbers contained in that array.

Code I’m using:

<?php 

$host = "xxx";
$db   = "xxx";
$user = "xxx";
$pass = "xxx";

// conecta ao banco de dados
$con = mysql_pconnect($host, $user, $pass) or trigger_error(mysql_error(),E_USER_ERROR); 

// seleciona a base de dados em que vamos trabalhar
mysql_select_db($db, $con);

// cria a instrução SQL que vai selecionar os dados
$query = sprintf("SELECT totalPrice, Time FROM deposits ORDER BY Time ASC");

// executa a query
$dados = mysql_query($query, $con) or die(mysql_error());

// transforma os dados em um array
$linha = mysql_fetch_assoc($dados);

// calcula quantos dados retornaram
$total = mysql_num_rows($dados);
?>

<html>
    <head>
    <title>Investimentos</title>
</head>
<body>
<?php
    // se o número de resultados for maior que zero, mostra os dados
    if($total > 0) {
        // inicia o loop que vai mostrar todos os dados
        do {
?>
            <p><?=$linha['totalPrice']?>$</p>
<?php
        // finaliza o loop que vai mostrar os dados
        }while($linha = mysql_fetch_assoc($dados));
    // fim do if 
    }

?>
</body>
</html>
<?php
// tira o resultado da busca da memória
mysql_free_result($dados);

the result of this array is like this:

120$

-100$

400$

-150$

500$

-460$

100$

-290$

100$

-295$

120$

180$

-600$

-700$

-100$

1200$

100$

-200$

100$

600$

-120$

I need here at the end to be the total sum of those numbers, someone can help?

  • 1

    Deivid, I reversed the last issue of your question because the idea here is to keep the original question. Here we do not write "solved" on the question. If you have an answer that really helped you, mark it as accepted. If you arrived at the solution yourself, post the solution as an answer. So content is more organized and easier to find in the future by other people with similar problems.

2 answers

0


Create a variable that takes the sum of the array, for example:

int somaTotal;

somaTotal = somaTotal + atoi(linha[Indice])

Something like, I used atoi which is a C function that turns char into integer.

Try it like this:

$host = "xxx";
$db   = "xxx";
$user = "xxx";
$pass = "xxx";

$somaTotal = 0.0;

// conecta ao banco de dados
$con = mysql_pconnect($host, $user, $pass) or trigger_error(mysql_error(),E_USER_ERROR); 
// seleciona a base de dados em que vamos trabalhar
mysql_select_db($db, $con);
// cria a instrução SQL que vai selecionar os dados
$query = sprintf("SELECT totalPrice, Time FROM deposits ORDER BY Time ASC");
// executa a query
$dados = mysql_query($query, $con) or die(mysql_error());
// transforma os dados em um array
$linha = mysql_fetch_assoc($dados);
// calcula quantos dados retornaram
$total = mysql_num_rows($dados);
?>

<html>
    <head>
    <title>Investimentos</title>
</head>
<body>
<?php
    // se o número de resultados for maior que zero, mostra os dados
    if($total > 0) {
        // inicia o loop que vai mostrar todos os dados
        do {
?>
            $somaTotal += (float)$linha['totalPrice'];
<?php
        // finaliza o loop que vai mostrar os dados
        }while($linha = mysql_fetch_assoc($dados));
    // fim do if 
       print $somaTotal;
    }

?>
</body>
</html>
<?php
// tira o resultado da busca da memória
mysql_free_result($dados);
  • how to do this? I don’t know.

  • I edited the post, try to use the code I changed. What is missing is to show on the screen the sum

  • did not work. I changed a little seeking a better result and almost was, but still could not. <? $somaTotal += (int)$line['totalPrice']; ? > showed the round result without adding up the pennies.

  • Change to <? $somaTotal += (float)$line['totalPrice']; ? > So the cents will be added up. If you have any questions just talk

  • This means you need to set the variable before the loop. for example: $somaTotal = 0.0 Maybe it is being initialized with 0, start with 0.0 which indicates that there will be decimals

  • It was perfect. Is there any way to say thank you, score? And how do I post the result of how it was so that people with the same problem see the final code.

  • Yes, just click on the gray triangle above 0 in the post to score. You can edit my post even by placing the final code that solved your problem.

  • To click on the triangle I need to have 15 feedback, but I’ve already sorted the code the way it worked. thanks for the instructions.

  • Cool. That’s what we’re here for :)

  • 1

    @Rafael, in PHP don’t worry about converting char to numeric types, it already does it for you

  • What ease, I did not know it, because I am programmer C.

Show 6 more comments

0

you can use the array_sum example:

In the PHP:

$array = array(150,500,460,100,-290,100, 295,120,180,600,700,100,1200,100,200,100,600,-120);

echo array_sum($array);

 /*retorna a soma do array. se você informar o indice $linha['totalPrice']
 ira somar apenas os valores do indice TotalPrice */

In the Mysql:

    SELECT SUM(nome_coluna) AS valor_soma FROM nome_tabela;

You can even add other columns...

 SELECT SUM(nome_coluna1 + nome_coluna2) AS valor_total_soma FROM nome_tabela;

In the Php gets like this:

$result = mysql_query('SELECT SUM(nome_coluna1) AS valor_soma FROM nome_tabela'); 
$row = mysql_fetch_assoc($result); 
$sum = $row['valor_soma '];
  • the first option does not da, because I do not have the values, they are variables, the values are sql, which change all the time. The third option does not fit, as you can see in the example, has only 1 table that creates a loop.

  • does a var_dum($var) on the mysql output and edits your response with the array you receive so I improve my response

Browser other questions tagged

You are not signed in. Login or sign up in order to post.