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

查看:28
本文介绍了在 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
}

但我经常需要在遍历数组时查看下一个元素.我知道我可以使用 for 循环并通过它的索引 ($array[$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?

推荐答案

您可以使用 缓存迭代器用于此目的.

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

因此,当您对 $collection 执行 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天全站免登陆