【发布时间】:2012-06-19 22:38:51
【问题描述】:
我想在 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]);
}
问题是它没有正确迭代。我只得到一个元素。
我认为这是因为 next() 方法中的 ++$this->_position 代码没有任何效果,因为 _position 是一个字符串(关联数组的键)。
那么我怎样才能转到这种类型数组的下一个元素呢?
【问题讨论】:
-
出于好奇,您为什么不直接使用ArrayIterator?
-
你能显示更多你的代码吗?那将是 a) 你说
class XYZ implements Iteratorb) 你(尝试)使用它的部分。 -
“我定义了这些方法”——它被称为“从文档中按原样复制粘贴”;-)
-
如果这是一个持有数组的类,考虑实现
IteratorAggregate并在getIterator中为该数组返回一个ArrayIterator。