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

时间:2013-11-19 10:09:45

标签: 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()似乎不对。

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

我想到的唯一解决方案是使用当前数组的副本

$arr = ['a'=>'first', 'b'=>'second'];
$iter = new ArrayIterator( $arr );
// Do a bunch of iterations...
$iter->next();
var_dump($iter->current());
// ...
$arr2 = $iter->getArrayCopy();
$new_iter = new ArrayIterator( $arr2 );

while( $new_iter->key() != $iter->key() ) {
    var_dump($new_iter->current());
    $new_iter->next();    
}