如何在 foreach 循环中跳过元素
我想在前循环中跳过一些记录。
例如,循环中有 68 条记录。如何跳过 20 条记录并从记录 #21 开始?
我想在前循环中跳过一些记录。
例如,循环中有 68 条记录。如何跳过 20 条记录并从记录 #21 开始?
我想到了五种解决方案:
for 循环的问题在于键可能是字符串,也可能不是连续数字,因此您必须使用“双寻址”(或“表查找”,随心所欲地调用它)并通过数组的键访问数组。
// Initialize 25 items
$array = range( 1, 25, 1);
// You need to get array keys because it may be associative array
// Or it it will contain keys 0,1,2,5,6...
// If you have indexes staring from zero and continuous (eg. from db->fetch_all)
// you can just omit this
$keys = array_keys($array);
for( $i = 21; $i < 25; $i++){
echo $array[ $keys[ $i]] . "\n";
// echo $array[$i] . "\n"; // with continuous numeric keys
}
我不认为这是这样做的好方法(除了你有大型数组并对其进行切片或生成密钥数组会使用大量内存的情况,68肯定不是),但也许它会起作用::)
$i = 0;
foreach( $array as $key => $item){
if( $i++ < 21){
continue;
}
echo $item . "\n";
}
只需获取数组的一部分,并在正常的 foreach 循环中使用它。
$sub = array_slice( $array, 21, null, true);
foreach( $sub as $key => $item){
echo $item . "\n";
}
next()
如果您可以设置内部数组指针到21(假设在前面的foreach循环中,内部有break,不起作用,我已经检查了:P),则可以执行此操作(如果数组中的数据不起作用):$array[21]
=== false
while( ($row = next( $array)) !== false){
echo $row;
}
顺便说一句:我最喜欢哈克雷的答案。
数组编辑器
也许研究文档是这个最好的评论。
// Initialize array iterator
$obj = new ArrayIterator( $array);
$obj->seek(21); // Set to right position
while( $obj->valid()){ // Whether we do have valid offset right now
echo $obj->current() . "\n";
$obj->next(); // Switch to next object
}
$i = 0;
foreach ($query)
{
if ($i++ < 20) continue;
/* php code to execute if record 21+ */
}