Skip to content

Instantly share code, notes, and snippets.

@remcotolsma
Created April 29, 2015 09:05
Show Gist options
  • Save remcotolsma/27a8a5515e5320a2cbd3 to your computer and use it in GitHub Desktop.
Save remcotolsma/27a8a5515e5320a2cbd3 to your computer and use it in GitHub Desktop.
Group iterator class for PHP
<?php
/**
* Title: Group iterator
* Description:
* Copyright: Copyright (c) 2005 - 2015
* Company: Pronamic
* @author Remco Tolsma
* @version 1.0.0
* @doc http://www.koders.com/java/fidC979E43601174F16239536C65E101FCB0C32E609.aspx?s=idef%3Asort
*/
class GroupIterator extends IteratorIterator {
/**
* The number items within one group
*
* @var int
*/
private $number;
/**
* The current group
*
* @var array
*/
private $group;
/**
* Round
*
* @var boolean
*/
private $round;
/**
* The key
*
* @var int
*/
private $key;
///////////////////////////////////////////////////////////////////////////
/**
* Constructs and initializes an group iterator
* @param $iterator
* @param $number
* @param $round
* @param $classname
* @return unknown_type
*/
public function __construct(Traversable $iterator, $number, $round = false, $classname = null) {
parent::__construct($iterator, $classname);
$this->number = $number;
$this->round = $round;
$this->key = 0;
}
///////////////////////////////////////////////////////////////////////////
/**
* Group the current and next items
*/
private function group() {
$this->group = array();
for($i = 0; $i < $this->number && parent::valid(); $i++, parent::next()) {
$this->group[] = parent::current();
}
}
///////////////////////////////////////////////////////////////////////////
/**
* Return the current group
*
* @return array
*/
public function current() {
return $this->group;
}
///////////////////////////////////////////////////////////////////////////
/**
* Return the current key
*
* @return int
*/
public function key() {
return $this->key;
}
///////////////////////////////////////////////////////////////////////////
/**
* Group the next items
*/
public function next() {
$this->group();
$this->key++;
}
///////////////////////////////////////////////////////////////////////////
/**
* Check if there is a current element after calls to rewind() or next()
*/
public function valid() {
if($this->round) {
return parent::valid();
} else {
return !empty($this->group);
}
}
///////////////////////////////////////////////////////////////////////////
/**
* Rewind the iterator to the first element
*/
public function rewind() {
parent::rewind();
$this->group();
$this->key = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment