【问题标题】:Peek ahead when iterating an array in PHP在 PHP 中迭代数组时向前看
【发布时间】:2011-01-28 07:45:13
【问题描述】:

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

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

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

【问题讨论】:

    标签: php arrays foreach spl


    【解决方案1】:

    您可以为此使用CachingIterator。

    这是一个例子:

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

    CachingIterator 总是比内部迭代器落后一步:

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

    因此,当您在$collection 上执行foreach 时,内部 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() 获取缓存的结果。

    【讨论】:

    • +1 甚至不知道这些 ([x]Iterators) 存在,非常有用,尤其是 DirectoryIterator。下次我处理文件时,这将为我节省大量工作。谢谢:)
    • @Psytronic 他们真的很整洁。堆叠它们的能力允许非常酷和灵活的东西。不幸的是,文档记录不佳,但请查看phpro.org/tutorials/Introduction-to-SPL.html
    • 不幸的是,如果数组包含对象而不是字符串,则该解决方案不起作用。我得到以下异常:Catchable fatal error: Object of class MySampleClass could not be converted to string in /home/www/test.php on line 398
    • @pako 要么在 MySampleClass 中实现 __toString 方法,要么将 CachingIterator::TOSTRING_USE_CURRENT 作为 CachingIterator 构造函数中的第二个参数传递。
    • @pako 我不知道为什么它需要这一步,但显然它确实需要。不幸的是,目前迭代器的文档记录很差。我给出的解决方案是基于使用 PHP 的 Reflection API 和 Trial and Error。如果您担心迭代器会做一些它不应该做的事情,请确保使用 UnitTest。
    【解决方案2】:

    使用array_keys。

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

    【讨论】:

    • 当答案就在核心功能中时,为什么我要承担接受答案的所有复杂性来做这样一个基本的事情?谢谢。
    • 我喜欢这个答案,能够以数字方式引用项目有很多好处。
    【解决方案3】:

    您可以使用next 和prev 来迭代数组。 current 返回当前项目值,key 返回当前键。

    所以你可以这样做:

    while (key($array) !== null) {
        next($array); // set pointer to next element
        if (key($array) === null) {
            // end of array
        } else {
            $nextItem = current($array);
        }
        prev($array); // resetting the pointer to the current element
    
        // …
    
        next($array);
    }
    

    【讨论】:

    • 代码看起来很复杂,而且容易出错(“nexts/prevs”太多,可能会发生非常奇怪的事情......)。
    【解决方案4】:

    我知道这是一篇旧帖子,但我现在可以更好地解释当前/下一个/上一个内容。 示例:

    $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
    

    【讨论】:

    • 我认为如果 $array 中有虚假值,这将无法正确报告。
    【解决方案5】:

    我知道我可以使用 for 循环并通过其索引 ($array[$i+1]) 引用下一项,但它不适用于关联数组。

    考虑将您的关联数组转换为带有array_values() 的顺序索引数组,以便您使用简单的 for 循环解决方案。

    【讨论】:

      【解决方案6】:

      旧帖子,但我的两分钱:

      如果你想向前看,你真的需要问自己“我是否以最好的方式解决了这个问题。”

      您无需进行窥视即可解决所有窥视问题。您只需要在集合之前声明一个“$prevItem”引用并将其初始化为空。每次循环结束时,将 $prevItem 设置为您刚刚评估的当前数组项。实际上,不是提前达到峰值,而是在第二项开始执行真正的逻辑并使用 $prevItem 引用来执行操作。您通过注意 $prevItem 为空来跳过第一项。

      $prevItem = null;
      $prevKey = null;
      
      foreach($collection as $key => $val)
      {
           if($prevItem != null)
           {
                //do your operation here
           }
      
      
           $prevItem = $val;
           $prevKey = $key;
      }
      

      这是干净的代码,也是一种常见的模式。

      在您迭代底层数据结构时,请远离它们……这绝不是好的做法,而且您需要这样做的情况非常罕见。

      【讨论】:

      • 在大多数情况下你是对的,但我现在实际上正在开发一个应用程序,我需要显示有关循环的下一次迭代的信息,同时仍处于之前的迭代中。我承认这是一种独特的情况,但这种情况确实存在。
      • 请举例说明您的情况。在少数情况下,您无法重构循环以提前开始一个循环并查看以前的数据。我什至没有见过这样的情况证明自己是一个弱设计。
      • 我没有可以在此处粘贴的简洁代码示例,但我正在开发一个平台来优化设备交付路线。在一天的停靠点列表中,我们需要提供一些关于 Stop B 的信息以及循环的 Stop A 迭代中的信息。让这件事变得棘手的是“混合”部分。否则,您的 $prevItem 方法在这里会像在我之前使用过的许多其他上下文中一样有效。
      猜你喜欢
      • 2018-04-28
      • 1970-01-01
      • 2016-05-11
      • 2023-04-06
      • 2012-01-31
      • 2013-05-27
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多