下一个关联数组的迭代器方法

Ale*_*lex 15 php arrays iterator

我想在PHP迭代器中使用关联数组:

http://php.net/manual/en/class.iterator.php

可能吗?

我定义了这些方法:

  public function rewind(){    
    reset($this->_arr);
    $this->_position = key($this->_arr);
  }

  public function current(){    
    return $this->_arr[$this->_position];
  }

  public function key(){
    return $this->_position;
  }

  public function next(){    
    ++$this->_position;
  }

  public function valid(){    
    return isset($this->_arr[$this->_position]);
  }
Run Code Online (Sandbox Code Playgroud)

问题是它没有正确迭代.我只得到一个元素.

我认为这是因为++$this->_positionnext()方法中的代码没有任何影响,因为_position是一个字符串(关联数组的键).

那我怎么去这个类型的数组的下一个元素?

goa*_*oat 31

function rewind() {
    reset($this->_arr);
}

function current() {
    return current($this->_arr);
}

function key() {
    return key($this->_arr);
}

function next() {
    next($this->_arr);
}

function valid() {
    return key($this->_arr) !== null;
}
Run Code Online (Sandbox Code Playgroud)


sha*_*yyx 5

为什么不创建一个ArrayObject来自你的关联Array?然后你可以getIterator()从这个ArrayObject和调用key(),next()等就可以了,只要你想...

一些例子:

$array = array('one' => 'ONE', 'two' => 'TWO', 'three' = 'THREE');
// create ArrayObject and get it's iterator
$ao = new ArrayObject($my_array);
$it = $ao->getIterator();
// looping
while($it->valid()) {
    echo "Under key {$it->key()} is value {$it->current()}";
    $it->next();
}
Run Code Online (Sandbox Code Playgroud)

ArrayObject
ArrayIterator