Is my module logic correct for this loop?

So here is the template I'm looking for

from the final set, I want to get the first 2 values ​​for one set, then the following 4 for another set, then 2 for this first set, and then 4 for another set, etc.

grab 2 | grab 4 | grab 2 | grab 4 ...

$count = 0;
foreach ($listing as $entry){
  if ($count % 4 == 0){
       // add to 4-item set
  } else if ($count % 2 == 0){
       // add to 2-item set
  }
  $count++;
}

My confusion is that when $ count% 4 = 0, then $ count% 2 will also be = 0.

So I have to be safe before reaching the wrong module case (since both are true for any arbitrary number divisible by 4) by checking first if $ count% 4 == 0?

+3
source share
3 answers

If I understood correctly, your desired distribution is actually:

A A, B B B B, A A, B B B B, A A, B B B B, ...

, , basked A, - B:

if ($count % 6 < 2){
   // add to 2-item set
}
elseif ($count % 6 < 6){
   // add to 4-item set
}

if/elseif, , . < n % 6 :

$count % 6 =    0  1  2  3  4  5  0
        if =   <2 <2 <6 <6 <6 <6 <2
    basket =    A  A  B  B  B  B  A
+1

1, 2, 8, 14 ..

, 2, 4, 8 ..

2, 6, 12, 18 ..

4, 8, 12 ..

, 1 ((count-2) % 6) == 0

2 (count != 0) && (count % 6) == 0

-

$count = 0;
foreach ($listing as $entry){
  if ($count < 2){
       // add to 2-item set
  } else {
       // add to 4-item set
  }

  if ($count < 6) $count++; 
  else $count = 0;
}

2/4 :

$count = 0;
foreach ($listing as $entry){
  if ($count == 2){
       // add 2 items to 2-item set
  } elseif ($count == 6) {
       // add 4 items to 4-item set
  }

  if ($count < 6) $count++; 
  else $count = 0;
}
+1

, .

, ,

  • 6, , 6, , count - 6 set1, 4 - set2.
  • Use the logical switch when the switch is true, add elements to set 1, after 4 elements set the switch to false, and when the switch is false, add elements to set2 by flipping the switch when you add elements to set2 .
0
source

All Articles