牛牛在线工具

Iterator::rewind()

收录 8868 个 PHP 函数,含用途说明与用法示例。

Iterator::rewind()

将迭代器重置到第一个元素

函数名:Iterator::rewind() 函数说明:Iterator::rewind() 方法将迭代器重置到第一个元素。 适用版本:该函数在PHP 5 及以上版本中可用。 用法示例: <?php class MyIterator implements Iterator { private $position = 0; private $array = array( "first element", "second element", "third element", ); public function rewind() { $this->position = 0; } public function current() { return $this->array[$this->position]; } public function key() { return $this->position; } public function next() { ++$this->position; } public function valid() { return isset($this->array[$this->position]); } } $it = new MyIterator(); // 使用rewind()方法将迭代器重置到第一个元素 $it->rewind(); while($it->valid()) { echo $it->key() . ' => ' . $it->current() . "\n"; $it->next(); } ?> 输出结果: 0 => first element 1 => second element 2 => third element 在上述示例中,我们创建了一个自定义的迭代器类MyIterator,实现了Iterator接口的所有方法。在rewind()方法中,我们将迭代器的位置重置为0,使其指向第一个元素。然后,在while循环中,使用valid()方法检查迭代器是否还有下一个元素,如果有,则输出当前元素的键和值,并通过next()方法将迭代器移动到下一个元素。最终,输出了所有元素的键值对。