2013-12-09 104 views
11

我正在尋找一種方法來獲得foreach()中的下一個和下一個+ 1鍵/值對。例如:PHP數組獲取下一個鍵/值在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 
    } 

} 
+0

這是可能的工作的解決方案:http://stackoverflow.com/a/5096852/1022697 – qwertynl

+0

我將創建一個自定義的迭代器。 –

回答

8

您不能以這種方式訪問​​下一個值和下一個值。

但是你可以做同樣的事情:

$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 
    } 
} 
+0

我結束了使用這個,即使它沒有回答我的問題100% – danielb

-2

好笑的是,我有十年編程PHP(含年暫停),但我需要一個接一個走功能就在一週前。

您在這裏:next,prev,重置等。請參見「另請參閱」部分。此外,檢查array_keys()

0

看一看CachingIterator,因爲在這個答案說明:

Peek ahead when iterating an array in PHP

或者使用array_keys()是在張貼同樣的問題,例如,另一個答案

$keys = array_keys($array); 
for ($i = 0; $i < count($keys); $i++) { 
    $cur = $array[$keys[$i]]; 
    $next = $array[$keys[$i+1]]; 
} 
1

下面是做這件事:

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 
} 

例子:http://3v4l.org/IGCXW

需要注意的是這樣寫絕不會檢查你的原始數組中的最後一個元素的循環。這可能是固定的,但用你目前的邏輯來看,它似乎並不重要,因爲沒有「最多」元素來比較最後一個元素。

1

我發現與複雜性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

0

你不能簡單地「留在」循環。我懷疑你正在尋找比編寫自定義迭代器更簡單的方法。如果您只想忽略具有重複鍵的條目,則追蹤最後一個鍵並將其與當前鍵進行比較。

$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; 
}