简体   繁体   中英

Restart while loop after determined number of iterations

I'm stuck with this one, what I need to accomplish should be really simple but I'm really struggling to find the logic.

I need my code to concatenate items of an array, but only up to 40 of them, and then restart the loop with the next 40 items, and so on... until it reaches the end of the array.

This is what i got so far, but the result is not what i expected...

$length = sizeof($array);
$count1 = 0;

while($count1<$length){

    $count2 = 0;
    while($count2<40){
        foreach($array as $array){
            $arrayids = $array["id"];
            $arrayids .= ",";
            //echoing it out to see what the result is...
            echo $arrayids;
            $count2++;
        }
    }
$count1++;
}

My array looks something like this, though it consists of a huge amount of items:

    Array
(
    [2] => Array
        (
            [id] => 4UjZ7mTU
        )

    [3] => Array
        (
            [id] => 8UsngmTs
        )

    [4] => Array
        (
            [id] => 8UsngmTs
        )

)

you can easily use array_chunk here and than iterate over the chunks like so:

$chunks = array_chunk($array, 40);

foreach($chunks as $chunk) {
  foreach ($chunk as $item) {
    //code here;
  }
}

Or in a single while loop:

$MAX = 3;
$LIST = [1,2,3,4,5,6,7,8,9,10];
$i = 0;
$n = count($LIST);

while ($i < $n) { 
  $base = floor($i/ $MAX);
  $offset = $i % $MAX;

  echo $LIST[($base * $MAX) + $offset];

  $i++;
}

您在第1行中拼错了“ $ lenght”,这是在给您带来意想不到的结果吗?

Rather than doing it the way you are doing, perhaps you should chunk your array. Example:

<?php

// Create a similar data format.
foreach(range(1,20) as $num)
    $data[]=['id' => $num];

// Output example format for the reader.
var_export(array_slice($data, 0, 3));

$ids = array_column($data, 'id');

// Now let's chunk the ids into fours
foreach(array_chunk($ids, 4) as $chunk)
    echo "\n" . implode(' ', $chunk);

Output:

array (
  0 => 
  array (
    'id' => 1,
  ),
  1 => 
  array (
    'id' => 2,
  ),
  2 => 
  array (
    'id' => 3,
  ),
)
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM