tôi đã tìm thấy các giải pháp với độ phức tạp O(n)
và không yêu cầu tìm kiếm thông qua các mảng trở lại và chuyển tiếp:
$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();
}
Chỉ cần nhớ để kiểm tra valid()
nếu bạn có kế hoạch để chuyển tiếp trên $next_val
và $next_next_val
.
Nguồn
2013-12-09 20:35:34
Đây là giải pháp có thể hoạt động: http://stackoverflow.com/a/5096852/1022697 – qwertynl
Tôi sẽ tạo trình vòng lặp tùy chỉnh cho điều đó. –