Add previous value to current one (FOREACH - PHP)

Asked

Viewed 35 times

-2

My doubt is very simple.

Problem: I have a repeating loop foreach, and in this repeating loop I separate the dates ($data['DATA'] is where I separate) and at each value found it should add the current value to the previous one of the same date (because there are many records on the same day), my problem is that I’m not getting the previous value of that same date.

Example:

foreach ($indices as $dados)
  {
      $retorno['semana'][$dados['DATA']][] = calcula(count($dados['NOTA']-1), $dados['NOTA']);
  }

Function Calculates:

function calculaHoras($valor_anterior, $valor_atual)
{
  $resultado = $valor_anterior + $valor_atual;
}

1 answer

0

For a repeat loop to take the previous value to save, we have the following example

$valorInicial = 0;
foreach($array as $key => $value) {
   $valorInicial = $valorInicial + $value;
}

So you would always be updating the initial value with the sum.

In this case of yours I understand it would look like this

$valorInicial = 0;
foreach($indices as $dados) {
   $valorInicial = $valorInicial + $dados['NOTA'];
}
$retorno['semana'][$dados['DATA']][] = $valorInicial;

Browser other questions tagged

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