php 如何跳过foreach循环中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9387193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:42:04  来源:igfitidea点击:

how to skip elements in foreach loop

phpfor-loop

提问by Utku Dalmaz

I want to skip some records in a foreach loop.

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

For example, there are 68 records in the loop. How can I skip 20 records and start from record #21?

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

回答by Vyktor

Five solutions come to mind:

想到了五个解决方案:

Double addressing via array_keys

通过 array_keys 进行双重寻址

The problem with for loops is that the keys may be strings or not continues numbers therefore you must use "double addressing" (or "table lookup", call it whatever you want) and access the array via an array of it's 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
}



Skipping records with foreach

使用 foreach 跳过记录

I don't believe that this is a good way to do this (except the case that you have LARGE arrays and slicing it or generating array of keys would use large amount of memory, which 68 is definitively not), but maybe it'll work: :)

我不相信这是一个很好的方法来做到这一点(除非你有大数组并对其进行切片或生成键数组会使用大量内存,而 68 绝对不是),但也许它会工作: :)

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



Using array slice to get sub part or array

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

Just get piece of array and use it in normal foreach loop.

只需获取一块数组并在正常的 foreach 循环中使用它。

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



Using next()

使用 next()

If you could set up internal array pointer to 21 (let's say in previous foreach loop with break inside, $array[21]doesn't work, I've checked :P) you could do this (won't work if data in array === false):

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

while( ($row = next( $array)) !== false){
  echo $row;
}

btw: I like hakre's answer most.

顺便说一句:我最喜欢 hakre 的回答。



Using ArrayIterator

使用 ArrayIterator

Probably studying documentation is the best comment for this one.

可能学习文档是对这个最好的评论。

// 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
}

回答by Mat Taylor

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

  /* php code to execute if record 21+ */
}

回答by Md. Sahadat Hossain

if want to skipped some index then make an array with skipped index and check by in_arrayfunction inside the foreachloop if match then it will be skip.

如果想跳过某个索引,则创建一个具有跳过索引的数组,并通过循环in_array内的函数检查,foreach如果匹配,则将跳过该数组。

Example:

例子:

//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
}

回答by hakre

You have not told what "records" actually is, so as I don't know, I assume there isa RecordIteratoravailable (if not, it is likely that there is some other fitting iterator available):

你还没有告诉什么是“记录”,其实就是这样,我不知道,我想有一个RecordIterator可用的(如果不是,很可能有一些其他的配件迭代可用):

$recordsIterator = new RecordIterator($records);
$limited = new LimitIterator($recordsIterator, 20);
foreach($limited as $record)
{
    ...
}

The answer here is to use foreachwith a LimitIterator.

这里的答案是foreachLimitIterator.

See as well: How to start a foreach loop at a specific index in PHP

另请参阅:如何在 PHP 中的特定索引处启动 foreach 循环

回答by Jazz

I'm not sure why you would be using a foreachfor this goal, and without your code it's hard to say whether this is the best approach. But, assuming there is a good reason to use it, here's the smallest version I can think of off the top of my head:

我不确定你为什么要使用 aforeach来实现这个目标,如果没有你的代码,很难说这是否是最好的方法。但是,假设有充分的理由使用它,这是我能想到的最小版本:

$count = 0;
foreach( $someArray as $index => $value ){
    if( $count++ < 20 ){
        continue;
    }

    // rest of foreach loop goes here
}

The continuecauses the foreachto skip back to the beginning and move on to the next element in the array. It's extremely useful for disregarding parts of an array which you don't want to be processed in a foreachloop.

continue导致foreach跳过回到开始,并移动到所述阵列中的下一个元素。它对于忽略不想在foreach循环中处理的数组部分非常有用。

回答by jakx

for($i = 20; $i <= 68; $i++){
//do stuff
}

This is better than a foreach loop because it only loops over the elements you want. Ask if you have any questions

这比 foreach 循环要好,因为它只循环你想要的元素。询问您是否有任何问题

回答by Tony Ventura

    array.forEach(function(element,index){
        if(index >= 21){
            //Do Something
        }
    });

Element would be the current value of index. Index increases with each turn through the loop. IE 0,1,2,3,4,5; array[index];

元素将是索引的当前值。索引随着循环的每转而增加。IE 0,1,2,3,4,5; 数组[索引];