Separate array by a certain value

0

I have an array with the jump number and its value. I need to make a count of the jump value until it reaches 4.00. And continue this count until the end of the jump.

salto   1   =>  2,00
salto   2   =>  2,00
salto   3   =>  2,00
salto   4   =>  2,00
salto   5   =>  2,00
salto   6   =>  2,00
salto   7   =>  2,00
salto   8   =>  2,00
salto   9   =>  2,00
salto   10  =>  2,00

The end result should be:

Salto 2 => 4,00
Salto 4 => 4,00
Salto 6 => 4,00
Salto 8 => 4,00
Salto 10 => 4,00

This is only a basis for understanding, the number of jumps can vary and the value can also.

    
asked by anonymous 22.09.2017 / 21:38

1 answer

2

Just make a foreach by adding the previous values until it reaches 4 :

// Seu array:
$arr = array_fill(1, 10, 2);

$total = 0;     
foreach($arr as $i => $item){
    $total += $item;

    if($total >= 4){
        $narr[$i] = $total;
        $total = 0;
    }
}

Result (using var_dump($narr) ):

array(5) {
  [2]=>
  int(4)
  [4]=>
  int(4)
  [6]=>
  int(4)
  [8]=>
  int(4)
  [10]=>
  int(4)
}

If this is really the "jump" has no special meaning, it is just any key, from 1 to 10 .

    
22.09.2017 / 22:36