如何跳过foreach循环中的元素

Utk*_*maz 23 php for-loop

我想在foreach循环中跳过一些记录.

例如,循环中有68条记录.如何跳过20条记录并从记录#21开始?

Vyk*_*tor 37

我想到了五种解决方案:

通过array_keys进行双重寻址

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
}
Run Code Online (Sandbox Code Playgroud)


使用foreach删除记录

我不相信这是一个很好的方法来做到这一点(除了你有LARGE数组并切片或生成密钥数组将使用大量内存的情况,其中68绝对不是),但也许它会工作::)

$i = 0;
foreach( $array as $key => $item){
    if( $i++ < 21){
        continue;
    }
    echo $item . "\n";
}
Run Code Online (Sandbox Code Playgroud)


使用数组切片获取子部件或数组

只需得到一块数组并在正常的foreach循环中使用它.

$sub = array_slice( $array, 21, null, true);
foreach( $sub as $key => $item){
    echo $item . "\n";
}
Run Code Online (Sandbox Code Playgroud)


运用 next()

如果你可以设置内部数组指针指向21(假设在之前的foreach循环中有内部中断,$array[21]不起作用,我检查过:P)你可以这样做(如果数组中的数据不会起作用=== false):

while( ($row = next( $array)) !== false){
  echo $row;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一下:我最喜欢hakre的回答.


运用 ArrayIterator

可能学习文档是这篇文章的最佳评论.

// 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
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*lor 15

$i = 0;
foreach ($query)
{
  if ($i++ < 20) continue;

  /* php code to execute if record 21+ */
}
Run Code Online (Sandbox Code Playgroud)


Md.*_*ain 5

如果要跳过某些索引,则使用跳过的索引创建一个数组,并通过循环in_array内的函数检查foreach是否匹配,然后将其跳过。

例:

//you have an array like that
$data = array(
    '1' => 'Hello world',
    '2' => 'Hello world2',
    '3' => 'Hello world3',
    '4' => 'Hello world4',
    '5' => 'Hello world5',// you want to skip this
    '6' => 'Hello world6',// you want to skip this
    '7' => 'Hello world7',
    '8' => 'Hello world8',
    '9' => 'Hello world8',
    '10' => 'Hello world8',//you want to skip this
);

//Ok Now wi make an array which contain the index wich have to skipped

$skipped = array('5', '6', '10');

foreach($data as $key => $value){
    if(in_array($key, $skipped)){
        continue;
    }
    //do your stuf
}
Run Code Online (Sandbox Code Playgroud)