Separate array by a certain value

Asked

Viewed 71 times

0

I have an array with the jump number and its value. I need to count the value of the jump 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 final 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 tbm can.

  • 1

    But this jump is using either total or two in two or something else? What do you take into account to know the timing of the jump?

  • 1

    Can you give a better example? that one didn’t make much sense. Why The jumps went to the value 4? How would be calculated this value?

  • for example: jump 1 and jump 2, adding their values gives 4, then the value 4 was in jump 2.

  • But always add 2 to 2 jumps ?

1 answer

2


Just make a foreach adding up 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’s just some key, from 1 until 10.

  • humm...array_fill, I’ll implement here to see if you arrive at the result I want...for now obg.. then I’ll come back to say if it worked really well.

Browser other questions tagged

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