Skip to content

Instantly share code, notes, and snippets.

@TheDistantSea
Last active December 20, 2015 02:09
Show Gist options
  • Select an option

  • Save TheDistantSea/6054423 to your computer and use it in GitHub Desktop.

Select an option

Save TheDistantSea/6054423 to your computer and use it in GitHub Desktop.
ZipIterator: iterates over multiple traversables in parallel. Requirements: PHP 5.4
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