ho trovato la soluzione con la complessità O(n)
e non richiede che cercano attraverso la gamma avanti e indietro:
$a = array('leg1'=>'LA', 'leg2'=>'NY', 'leg3'=>'NY', 'leg4'=>'FL');
// initiate the iterator for "next_val":
$nextIterator = new ArrayIterator($a);
$nextIterator->rewind();
$nextIterator->next(); // put the initial pointer to 2nd position
// initiaite another iterator for "next_next_val":
$nextNextIterator = new ArrayIterator($a);
$nextNextIterator->rewind();
$nextNextIterator->next();
$nextNextIterator->next(); // put the initial pointer to 3rd position
foreach($a AS $k => $v){
$next_val = $nextIterator->current();
$next_next_val = $nextNextIterator->current();
echo "Current: $v; next: $next_val; next_next: $next_next_val" . PHP_EOL;
$nextIterator->next();
$nextNextIterator->next();
}
Basta ricordare per verificare valid()
se si prevede di trasmettere sulla $next_val
e $next_next_val
.
fonte
2013-12-09 20:35:34
Ecco una soluzione che potrebbe funzionare: http://stackoverflow.com/a/5096852/1022697 – qwertynl
vorrei creare un iteratore personalizzato per questo. –