我正在寻找一种方法,在foreach()中获取下一个和下一个之后的键/值对。例如:
$a = array('leg1'=>'LA', 'leg2'=>'NY', 'leg3'=>'NY', 'leg4'=>'FL');
foreach($a AS $k => $v){
if($nextval == $v && $nextnextval == $v){
//staying put for next two legs
}
}
我正在寻找一种方法,在foreach()中获取下一个和下一个之后的键/值对。例如:
$a = array('leg1'=>'LA', 'leg2'=>'NY', 'leg3'=>'NY', 'leg4'=>'FL');
foreach($a AS $k => $v){
if($nextval == $v && $nextnextval == $v){
//staying put for next two legs
}
}
您无法访问下一个和下下个值的方法。
但是您可以做类似的操作:
$a = array('leg1'=>'LA', 'leg2'=>'NY', 'leg3'=>'NY', 'leg4'=>'FL');
$keys = array_keys($a);
foreach(array_keys($keys) AS $k ){
$this_value = $a[$keys[$k]];
$nextval = $a[$keys[$k+1]];
$nextnextval = $a[$keys[$k+2]];
if($nextval == $this_value && $nextnextval == $this_value){
//staying put for next two legs
}
}
我找到了一个复杂度为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();
}
只要记得在计划依赖于 $next_val
和 $next_next_val
的情况下测试 valid()
。
Here's one way to do it:
while($current = current($a)) {
$next = next($a);
$nextnext = next($a);
// Comparison logic here
prev($a); // Because we moved the pointer ahead twice, lets back it up once
}
请注意,这种方式编写的循环永远不会检查原始数组中的最后一个元素。虽然可以修复这个问题,但是根据您目前的逻辑,似乎没有关系,因为没有“更多”的元素来将其与最后一个元素进行比较。
$keys = array_keys($array);
for ($i = 0; $i < count($keys); $i++) {
$cur = $array[$keys[$i]];
$next = $array[$keys[$i+1]];
}
在循环中,你不能简单地“原地不动”。我猜你想做的事情比编写自定义迭代器要容易得多。如果你只是想忽略具有重复键的条目,那么跟踪上一个键并将其与当前键进行比较即可。
$a = array('leg1'=>'LA', 'leg2'=>'NY', 'leg3'=>'NY', 'leg4'=>'FL');
// Prints LA NY FL
$last_v = null;
foreach ( $a as $k => $v ){
if ( $last_v == $v ) {
/**
* Duplicate value, so skip it
*/
continue;
}
echo $v.' ';
$last_v = $v;
}