php - 在确定的迭代次数后重新启动 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
)
)
解决方案
您可以在这里轻松使用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++;
}
推荐阅读
- excel - Excel:在长度的中间找到
- android - 如何完全删除选项卡中的活动选项卡指示器?
- angular - 在严格模式下,一个对象字面量不能有多个同名的属性。属性“路径”说是重复的
- python - 无头 Chrome 驱动程序无法在 python Selenium 驱动程序中获取 Instagram 页面
- mysql - 使用 Laravel Sai 设置跨数据库外键
- flutter - 参数类型“字符串?” 不能分配给参数类型“字符串”
- php - PHP Preg 匹配所有 m3u8 以解析成数组
- c# - 如何在 C# 中使用 void *buffer 定义 c++ 函数的 dllimport
- java - Firebase 实时数据库延迟
- node.js - 由于节点是异步的,因此难以查询数据库