PHP : Function Reference : Standard PHP Library (SPL) Functions : ArrayIterator::seek
adar
Nice way to get previous and next keys:
<?php
class myIterator extends ArrayIterator{
private $previousKey;
public function __construct( $array ) {
parent::__construct( $array );
$this->previousKey = NULL;
}
public function getPreviousKey() {
return $this->previousKey;
}
public function next() {
$this->previousKey = $this->key();
parent::next();
}
public function getNextKey() {
$key = $this->current()-1;
parent::next();
if ( $this->valid() ) {
$return = $this->key();
} else {
$return = NULL;
}
$this->seek( $key );
return $return;
}
}
class myArrayObject extends ArrayObject {
private $array;
public function __construct( $array ) {
parent::__construct( $array );
$this->array = $array;
}
public function getIterator() {
return new myIterator( $this->array );
}
}
?>
And for testing:
<?php
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
$arrayObject = new myArrayObject( $array );
for ( $i = $arrayObject->getIterator() ; $i->valid() ; $i->next() ) {
print "iterating...\n";
print "prev: ".$i->getPreviousKey()."\n";
print "current: ".$i->key()."\n";
print "next: ".$i->getNextKey()."\n";
}
?>
Output will be:
iterating...
prev:
current: a
next: b
iterating...
prev: a
current: b
next: c
iterating...
prev: b
current: c
next:
|