2010-10-02 81 views
10

我基本上需要一些foreach循环内的东西,它会跳过数组的前10次迭代。让foreach跳过迭代

foreach($aSubs as $aSub){ 
    if($iStart > '0') 
    //Skip first $iStart iterations. Start at the next one 
} 

感谢

回答

25

启动计数器,并使用continue跳过前十次的循环:

$counter = 0 ; 
foreach($aSubs as $aSub) { 
    if($counter++ < 10) continue ; 
    // Loop code 
} 
+1

完美的作品。真是个好主意。谢谢 – tmartin314 2010-10-02 22:36:37

2

使用迭代器:

$a = array('a','b','c','d'); 
$skip = 2; 
foreach (new LimitIterator(new ArrayIterator($a), $skip) as $e) 
{ 
    echo "$e\n"; 
} 

输出:

c 
d 

或者使用索引(如果阵列具有从0整数密钥.. N-1):

foreach ($a as $i => $e) 
{ 
    if ($i < $skip) continue; 
    echo "$e\n"; 
} 
0

如果$ ASUBS是未实现迭代一个类的一个对象,和该指数是连续的整数(从零开始),它会更容易:

$count = count($aSubs); 
for($i = 9, $i < $count; $i++) { 
    // todo 
} 
0

其实,你并不需要使用foreach回路L1的优势来声明另一个变量$counter关键字:

foreach ($aSubs as $index => $aSub) { 
    if ($index < 10) continue; 
    // Do your code here 
} 

这比在foreach循环外声明另一个变量更好。