在 PHP 5.2 中迭代数组时是否可以“向前查看”?例如,我经常使用 foreach 来操作数组中的数据:

foreach($array as $object) {
  // do something
}

但我经常需要在浏览数组时查看下一个元素。我知道我可以使用 for 循环并通过索引引用下一个项目($array[$i+1]),但它不适用于关联数组。对于我的问题是否有任何优雅的解决方案,可能涉及 SPL?

有帮助吗?

解决方案

可以使用 CachingIterator 用于此目的。

下面是一个例子:

$collection = new CachingIterator(
                  new ArrayIterator(
                      array('Cat', 'Dog', 'Elephant', 'Tiger', 'Shark')));

在CachingIterator总是内迭代后面一个步骤:

var_dump( $collection->current() ); // null
var_dump( $collection->getInnerIterator()->current() ); // Cat

因此,当你foreach$collection,内ArrayIterator的当前元素将是下一个元素已经,允许你窥视它:

foreach($collection as $animal) {
     echo "Current: $animal";
     if($collection->hasNext()) {
         echo " - Next:" . $collection->getInnerIterator()->current();
     }
     echo PHP_EOL;
 }

将输出:

Current: Cat - Next:Dog
Current: Dog - Next:Elephant
Current: Elephant - Next:Tiger
Current: Tiger - Next:Shark
Current: Shark

出于某种原因,我无法解释,该CachingIterator总是会尝试将当前元素转换为字符串。如果你想遍历一个对象集合,并需要访问性能的方法,通过CachingIterator::TOSTRING_USE_CURRENT作为第二个参数去构造。


在旁注中,CachingIterator得到它的从缓存所有已经重复了迄今为止结果的能力名字。对于这个工作,你有CachingIterator::FULL_CACHE实例,然后你可以用getCache()获取缓存的结果。

其他提示

使用array_keys

$keys = array_keys($array);
for ($i = 0; $i < count($keys); $i++) {
    $cur = $array[$keys[$i]];
    $next = $array[$keys[$i+1]];
}

您可以使用 nextprev 迭代一个数组。 current 返回当前项目值并 key 当前的密钥。

所以你可以这样做:

while (key($array) !== null) {
    next($array);
    if (key($array) === null) {
        // end of array
    } else {
        $nextItem = value($array);
    }
    prev($array);

    // …

    next($array);
}

我知道这是旧的文章,但我可以解释一下当前/下一首/上一个更好的事情了。 例如:

$array = array(1,2,3,2,5);

foreach($array as $k => $v) {
    // in foreach when looping the key() and current() 
    // is already pointing to the next record
    // And now we can print current
    print 'current key: '.$k.' and value: '.$v;
    // if we have next we can print its information too (key+value)
    if(current($array)) {
         print ' - next key: '.key($array).' and value: '.current($array);
         // at the end we must move pointer to next
         next($array);
    }
    print '<br>';
}

// prints:
// current key: 0 and value: 1 - next key: 1 and value: 2
// current key: 1 and value: 2 - next key: 2 and value: 3
// current key: 2 and value: 3 - next key: 3 and value: 2
// current key: 3 and value: 2 - next key: 4 and value: 5
// current key: 4 and value: 5
  

我知道我可以使用一个for循环和通过索引($阵列[$ I + 1])的参考的下一个项目,但它不会对关联数组工作。

考虑关联数组转换成顺序索引一个与 array_values(),让您使用简单的for循环溶液。

scroll top