如何跳过foreach循环中的元素

时间:2022-03-29 21:22:22

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开始?

7 个解决方案

#1


34  

Five solutions come to mind:

我想到了五种解决方案:

Double addressing via 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

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: :)

我不相信这是一个很好的方法来做到这一点(除了你有LARGE数组并切片或生成密钥数组将使用大量内存的情况,其中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()

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循环中有break,$ array [21]不起作用,我检查过:P)你可以这样做(如果数据在array === false):

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

btw: I like hakre's answer most.

顺便说一句:我最喜欢哈克尔的回答。


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

#2


13  

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

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

#3


4  

if want to skipped some index then make an array with skipped index and check by in_array function inside the foreach loop if match then it will be skip.

如果想跳过某个索引然后创建一个跳过索引的数组,并在foreach循环中检查in_array函数,如果匹配则将跳过。

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
}

#4


3  

You have not told what "records" actually is, so as I don't know, I assume there is a RecordIterator available (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 foreach with a LimitIterator.

这里的答案是使用foreach和LimitIterator。

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

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

#5


1  

I'm not sure why you would be using a foreach for 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:

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

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

    // rest of foreach loop goes here
}

The continue causes the foreach to 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 foreach loop.

继续使foreach跳回到开头并继续到数组中的下一个元素。它对于忽略不希望在foreach循环中处理的数组部分非常有用。

#6


0  

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循环更好,因为它只遍历你想要的元素。问你是否有任何问题

#7


0  

    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;阵列[指数];

#1


34  

Five solutions come to mind:

我想到了五种解决方案:

Double addressing via 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

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: :)

我不相信这是一个很好的方法来做到这一点(除了你有LARGE数组并切片或生成密钥数组将使用大量内存的情况,其中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()

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循环中有break,$ array [21]不起作用,我检查过:P)你可以这样做(如果数据在array === false):

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

btw: I like hakre's answer most.

顺便说一句:我最喜欢哈克尔的回答。


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

#2


13  

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

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

#3


4  

if want to skipped some index then make an array with skipped index and check by in_array function inside the foreach loop if match then it will be skip.

如果想跳过某个索引然后创建一个跳过索引的数组,并在foreach循环中检查in_array函数,如果匹配则将跳过。

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
}

#4


3  

You have not told what "records" actually is, so as I don't know, I assume there is a RecordIterator available (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 foreach with a LimitIterator.

这里的答案是使用foreach和LimitIterator。

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

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

#5


1  

I'm not sure why you would be using a foreach for 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:

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

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

    // rest of foreach loop goes here
}

The continue causes the foreach to 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 foreach loop.

继续使foreach跳回到开头并继续到数组中的下一个元素。它对于忽略不希望在foreach循环中处理的数组部分非常有用。

#6


0  

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循环更好,因为它只遍历你想要的元素。问你是否有任何问题

#7


0  

    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;阵列[指数];