lundi 20 juin 2016

Is it possible to select a different item within foreach loop?

I have an array of columns and want to divide them into rows.

To simplify it, I will write them out as numbers and this is just a pseudo code and will not work, probably:

$columns = [2, 4, 4, 4, 2, 4, 4, 2]

What I want to achieve is a foreach loop like this:

```

$rows = [];
$rowIndex = 0;
$counter = 0;
foreach ($columns as $column) {
   if ($counter + $column > 12) {
      // select a different item from the columns array but at the same time, unset it as it shouldn't
      // be looped over again, if we use it within this if statement. Hope that makes sense.

      // I tried this, but array_shift does not seem to remove the item from the list. it still leave there for foreach loop to loop over it later on..
      $try = array_shift( array_filter($columns, function($c) {return $c < 4; }) );

      $column = $try ?? $column;



      if (!$try) { $rowIndex++; }
   }

   $rows[$rowIndex][] = $column;
}

P.S. I am using Laravel, so I could leverage collections if there is a solution to this..



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire