我怎样在一个ArrayIterator复制到preserve这是当前迭代的位置? [英] How do I copy an ArrayIterator to preserve it's current iteration position?

查看:94
本文介绍了我怎样在一个ArrayIterator复制到preserve这是当前迭代的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于这似乎是我必须做的就是这样的效果:

Because this seems like what I have to do to get this effect:

$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();
}

编辑:此外,仅仅是明确的,如果我无法修改与基本阵列未设置()?我的数字数组迭代器存储自己的基地阵列的复制,因此,使用 offsetUnset()看起来不正确。

Also, just to be clear, should I NOT be modifying the base array with unset()? I figure the array iterator stores its own copy of the base array, so using offsetUnset() doesn't seem right.

推荐答案

ArrayIterator 不实现告诉()函数,但是你可以效仿一下,然后使用的 求() 去的位置你想要的。下面是做到了这一点继承类:

ArrayIterator does not implement a tell() function, but you can emulate this, and then use seek() to go to the position you want. Here's an extended class that does just that:

<?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

此外,还可以使用自定义复制()函数来克隆对象:

Alternately, you can use the custom copy() function to clone the object:

<?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

这篇关于我怎样在一个ArrayIterator复制到preserve这是当前迭代的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆