我想跳过一些foreach循环的迭代。
我有这段代码;
$myarray = array("a","b","c","d","e","f","g","h");
$skip = 5;
foreach($myarray as $key => $letter){
if($key < $skip){
$key = $skip;
}
echo $letter;
}
此代码不起作用。但有了它,我可以解释我想要什么。我实际上移动了下一次迭代的指针。它认为通过将密钥的值修改为我想要的那个就足够了。我知道可能的解决方案就是这个。
$myarray = array("a","b","c","d","e","f","g","h");
$skip = 5;
foreach($myarray as $key => $letter){
if($key < $skip){
continue;
}
echo $letter;
}
但是那种情况仍然是迭代步骤。我想完全跳过迭代。
由于
答案 0 :(得分:2)
请参阅:array_slice
$myarray = array("a","b","c","d","e","f","g","h");
foreach(array_slice($myarray, 5) as $key => $letter){
echo $letter;
}
答案 1 :(得分:1)
您可以使用for循环
编辑:
for($i = $skip; $skip > 0, $i < count($myarray); $i++) {
// do some stuff
}
答案 2 :(得分:0)
这并不是foreach
循环(以及一般的迭代)的工作方式。
你可以做continue
版本(它工作正常;如果它是循环体中的第一件事,它基本上是相同的),或者你可以构造一个不同的数组来迭代不包括第一个元素,或者您可以使用常规for
循环。
答案 3 :(得分:0)
foreach (array_slice($myarray, 5) as $key => $letter) {
[...]
}
答案 4 :(得分:0)
<?php
$myarray = array("a","b","c","d","e","f","g","h");
$skip = 5;
$index = 0 ;
foreach($myarray as $key => $letter){
if( ($index % $skip) == 0 ){
echo $letter;
}
$index++;
}
?>
答案 5 :(得分:0)
$myarray = array("a","b","c","d","e","f","g","h");
foreach (new LimitIterator (new ArrayIterator ($myarray), 5) as $letter)
{
echo $letter;
}
答案 6 :(得分:0)
您可以$array->next()
次致电$skip
。有些情况下,您无法轻松使用常规for
循环:例如,在迭代DatePeriod
对象时。