首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何复制ArrayIterator以保持它当前的迭代位置?

如何复制ArrayIterator以保持它当前的迭代位置?
EN

Stack Overflow用户
提问于 2013-11-19 10:09:44
回答 2查看 565关注 0票数 3

因为这似乎是我必须做的才能达到这样的效果:

代码语言:javascript
复制
$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()似乎不合适。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-19 10:35:33

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

代码语言:javascript
复制
<?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;
        }
    }
?>

使用:

代码语言:javascript
复制
<?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()函数克隆对象:

代码语言:javascript
复制
<?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

票数 4
EN

Stack Overflow用户

发布于 2013-11-19 10:27:46

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

代码语言:javascript
复制
$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();    
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20068602

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档