Last active
December 20, 2015 02:09
-
-
Save TheDistantSea/6054423 to your computer and use it in GitHub Desktop.
ZipIterator: iterates over multiple traversables in parallel. Requirements: PHP 5.4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class ZipIterator implements \Iterator | |
| { | |
| private $_iterators; | |
| public function __construct() | |
| { | |
| foreach (func_get_args() as $traversable) { | |
| if (is_array($traversable)) { | |
| $this->_iterators[] = new \ArrayIterator($traversable); | |
| } | |
| else if ($traversable instanceof \Traversable) { | |
| $this->_iterators[] = $traversable; | |
| } | |
| else { | |
| throw new Exception("All arguments to ".__CLASS__." must be arrays or implement Traversable."); | |
| } | |
| } | |
| } | |
| public function current() | |
| { | |
| $result = []; | |
| foreach ($this->_iterators as $iterator) { | |
| $result[] = $iterator->current(); | |
| } | |
| return $result; | |
| } | |
| public function next() | |
| { | |
| foreach ($this->_iterators as $iterator) { | |
| $iterator->next(); | |
| } | |
| } | |
| public function key() | |
| { | |
| $result = []; | |
| foreach ($this->_iterators as $iterator) { | |
| $result[] = $iterator->key(); | |
| } | |
| return $result; | |
| } | |
| public function valid() | |
| { | |
| foreach ($this->_iterators as $iterator) { | |
| if ($iterator->valid()) { | |
| return true; | |
| } | |
| } | |
| return false; | |
| } | |
| public function rewind() | |
| { | |
| foreach ($this->_iterators as $iterator) { | |
| $iterator->rewind(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment