想到五个解决方案:
通过 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
}
使用 foreach 跳过记录
我不认为这是一个好方法(除非您有 LARGE 数组并对其进行切片或生成键数组会使用大量内存,而 68 绝对不是),但也许它会起作用的::)
$i = 0;
foreach( $array as $key => $item){
if( $i++ < 21){
continue;
}
echo $item . "\n";
}
使用数组切片获取子部分或数组
只需获取一块数组并在正常的 foreach 循环中使用它。
$sub = array_slice( $array, 21, null, true);
foreach( $sub as $key => $item){
echo $item . "\n";
}
使用next()
如果您可以设置指向 21 的内部数组指针(假设在之前的 foreach 循环中,内部有 break,$array[21] 不起作用,我已经检查过 :P)您可以这样做(如果数据无效,则不会起作用在数组=== false):
while( ($row = next( $array)) !== false){
echo $row;
}
btw:我最喜欢 hakre 的回答。
可能研究文档是对此的最佳评论。
// 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
}