php - 如何复制 ArrayIterator 以保留其当前迭代位置?

标签 php arrays iterator copy

因为这似乎是我必须做的才能获得这种效果:

$arr = ['a'=>'first', 'b'=>'second', ...];
$iter = new ArrayIterator( $arr );

// Do a bunch of iterations...
$iter->next();
// ...

$new_iter = new ArrayIterator( $arr );
while( $new_iter->key() != $iter->key() ) {
    $new_iter->next();
}

编辑:此外,为了清楚起见,我不应该使用 unset() 修改基本数组吗?我认为数组迭代器存储它自己的基本数组副本,因此使用 offsetUnset() 似乎不正确。

最佳答案

ArrayIterator没有实现 tell() 函数,但您可以模拟它,然后使用 seek()去你想要的位置。这是一个扩展类,它就是这样做的:

<?php
    class ArrayIteratorTellable extends ArrayIterator {
        private $position = 0;

        public function next() {
            $this->position++;
            parent::next();
        }

        public function rewind() {
            $this->position = 0;
            parent::rewind();
        }

        public function seek($position) {
            $this->position = $position;
            parent::seek($position);
        }

        public function tell() {
            return $this->position;
        }

        public function copy() {
            $clone = clone $this;
            $clone->seek($this->tell());
            return $clone;
        }
    }
?>

使用:

<?php
    $arr = array('a' => 'first', 'b' => 'second', 'c' => 'third', 'd' => 'fourth');
    $iter = new ArrayIteratorTellable( $arr );

    $iter->next();

    $new_iter = new ArrayIteratorTellable( $arr );

    var_dump($iter->current()); //string(6) "second"
    var_dump($new_iter->current()); //string(6) "first"

    $new_iter->seek($iter->tell()); //Set the pointer to the same as $iter

    var_dump($new_iter->current()); //string(6) "second"
?>

DEMO


或者,您可以使用自定义 copy() 函数克隆对象:

<?php
    $arr = array('a' => 'first', 'b' => 'second', 'c' => 'third', 'd' => 'fourth');
    $iter = new ArrayIteratorTellable( $arr );

    $iter->next();

    $new_iter = $iter->copy();

    var_dump($iter->current()); //string(6) "second"
    var_dump($new_iter->current()); //string(6) "second"
?>

DEMO

关于php - 如何复制 ArrayIterator 以保留其当前迭代位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20068602/

相关文章:

c++ - 在 C++ 中命名和使用迭代器的常规约定是什么?

php - 假数组切片操作符 : Make it shorter

arrays - 为什么在初始化指针时必须将数组转换为 type[]?

c++ - 我们可以安全地依赖迭代器 v.end() 的位置吗?

java - 将数组操作为新数组

Perl:if(列表中的元素)

java - 迭代器检索第一个值并将其放回同一个迭代器

php - 截断了不正确的 DOUBLE 值 : '12,11' '

php - Zend Framework 3 - 基于查询字符串的路由

php - 我需要帮助创建 SQL 查询