首页 > 解决方案 > 在确定的迭代次数后重新启动 while 循环

问题描述

我坚持这个,我需要完成的事情应该很简单,但我真的很难找到逻辑。

我需要我的代码来连接数组的项目,但最多只能连接 40 个,然后用接下来的 40 个项目重新启动循环,依此类推......直到它到达数组的末尾。

这是我到目前为止得到的,但结果不是我所期望的......

$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++;
}

我的数组看起来像这样,尽管它包含大量项目:

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

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

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

)

标签: phparrayswhile-loop

解决方案


您可以在这里轻松使用array_chunk,而不是像这样迭代块:

$chunks = array_chunk($array, 40);

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

或在单个 while 循环中:

$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++;
}

推荐阅读