我发现与复杂性O(n)
的解决方案,并不需要通过阵列寻求前进和后退:
$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();
}
只记得测试valid()
如果你打算中继的$next_val
和$next_next_val
。
这是可能的工作的解决方案:http://stackoverflow.com/a/5096852/1022697 – qwertynl
我将创建一个自定义的迭代器。 –