2015-10-31 38 views
0

我們怎樣才能向前或向後移動指針在foreach語句時,數組引用傳遞:當數組引用傳遞移動指針

foreach($array as $key => &$val){ 

    if($condition1 == true) **set pointer to previous element** 
    else **set pointer to previous to previous element**; 

    if($condition2 == true) **set pointer to next element** 
    else **set pointer to next to next element**; 
} 

EDIT1:如果我使用ArrayIterator我不得不改變很多的代碼,我想避免。

+1

檢查此http://stackoverflow.com/questions/10458848/php-how-to-move -array-pointer-inside-foreach-loop –

+0

如果我使用'ArrayIterator',我必須更改很多代碼,這是我想避免的。 –

+1

imo,但是,沒有什麼能阻止你自己保留'previous'和'next'指針,並在'foreach'中使用邏輯。我會試着寫一個'class'來完成你所需要的邏輯。我懷疑它比'foreach'長期'戰鬥'要容易得多。看'集合'? –

回答

0

在沒有其他簡單的解決方案,我最後修改代碼來實現ArrayIterator類,並改變了程序邏輯

$obj = new ArrayObject($arrayName); 
$it = $obj->getIterator(); 
foreach ($it as $key=>&$val){ 
    if(condition1){ 
    $it->offsetSet($it->key()+1,$arrayName[$key+2]); 
    } 
}