How to Calculate read values in an Array and store the calculation in a single PHP variable

Asked

Viewed 124 times

0

The array has the following structure below:

Array
(
    [0] => Array
        (
            [value] => 0
            [total] => 100
        )

    [1] => Array
        (
            [value] => 1
            [total] => 50
        )

    [2] => Array
        (
            [value] => 0
            [total] => 300
        )

    [3] => Array
        (
            [value] => 1
            [total] => 150
        )
)

The array that has the value index 0 will always be the total greater than the array that has the value index 1, so I need to scan and decrease the value of the total index of the array that has the value index 0 with the total of the array that has the value index 1, thus:

In the first loop make the calculation: $total = 100 - 50; $total = 50;

In the second loop make the calculation: $total = 300 - 150; $total = 150;

And at the end of all the loops have all the values that were subtracted summed and totaled, in the above example would be 200 (50, from the first loop + 150, from the second loop).

Does anyone know how to implement this logic in PHP to help me?

2 answers

0


I suggest changing the logic to simplify and perform the calculation in just one loop.

To make loops in PHP you can use while, foreach, for...

For example with a foreach.

$total = 0;
foreach ($array as $element) { 
   if ($element['value'] == 0) {
      $total += $element['total'];
   }else{
      $total -= $element['total'];
   }
}

Suggestions for references:
https://www.php.net/manual/en/language.control-structures.php

0

My suggestion is to walk by the "for" of 2 in 2 taking the value = 0 array and take the next position to perform the summation and save them in a new array to then do the new summation.

Follow the example below:

$arrInicial = [0 => ['value' => 0, 'total' => 100], 1 => ['value' => 1, 'total' => 50],
               2 => ['value' => 0, 'total' => 300], 3 => ['value' => 1, 'total' => 150]];
$n = count($arrInicial)/2;

$arrSoma = [];
$total = 0;
for ($i = 0; $i <= $n; $i = $i+2) {
  $arrSoma[]['total'] = $arrInicial[$i]['total'] - $arrInicial[$i+1]['total'];
  $total = $total + ($arrInicial[$i]['total'] - $arrInicial[$i+1]['total']);
}

echo $total;

Browser other questions tagged

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