迭代PHP中的数组时提前偷看 [英] Peek ahead when iterating an array in PHP

查看:126
本文介绍了迭代PHP中的数组时提前偷看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以偷看进取,而在迭代PHP 5.2数组?例如,我经常使用的foreach操作从阵列数据:

Is it possible to "peek ahead" while iterating an array in PHP 5.2? For example, I often use foreach to manipulate data from an array:

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

不过,我经常需要在下届元素偷看经历的阵列一会儿。我知道我可以使用循环,并通过它的索引引用的下一个项目( $阵列[$ I + 1] ),但它不会对关联数组。是否有我的问题,任何优雅的解决方案,可能涉及SPL?

But I often need to peek at the next element while going through the array. I know I could use a for loop and reference the next item by it's index ($array[$i+1]), but it wouldn't work for associative arrays. Is there any elegant solution for my problem, perhaps involving SPL?

推荐答案

您可以使用 CachingIterator 用于这一目的。

You can use the CachingIterator for this purpose.

下面是一个例子:

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

该CachingIterator始终是内部迭代落后一步:

The CachingIterator is always one step behind the inner iterator:

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

因此​​,当你做的foreach $集合,内ArrayIterator的当前元素将是未来元素已,让你窥视到其中:

Thus, when you do foreach over $collection, the current element of the inner ArrayIterator will be the next element already, allowing you to peek into it:

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 作为第二个参数来构造。


For some reason I cannot explain, the CachingIterator will always try to convert the current element to string. If you want to iterate over an object collection and need to access properties an methods, pass CachingIterator::TOSTRING_USE_CURRENT as the second param to the constructor.

在阿里纳斯的CachingIterator得到它的从缓存所有已遍历到目前为止结果的能力名字。对于这个工作,你有 CachingIterator :: FULL_CACHE 来实例化它,然后你可以用获取 getCache()

On a sidenote, the CachingIterator gets it's name from the ability to cache all the results it has iterated over so far. For this to work, you have to instantiate it with CachingIterator::FULL_CACHE and then you can fetch the cached results with getCache().

这篇关于迭代PHP中的数组时提前偷看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆