2011-06-20 195 views
11

獲取下一個數組項我有一個數組使用鑰匙PHP

Array(1=>'test',9=>'test2',16=>'test3'... and so on); 

我如何通過傳遞鍵獲得下一個數組項。

例如,如果我有密鑰9那麼我應該得到test3作爲結果。如果我有1那麼它應該返回'test2'作爲結果。

編輯,以使其更清晰

echo somefunction($array,9); //result should be 'test3' 
function somefunction($array,$key) 
{ 
    return $array[$dont know what to use]; 
} 
+0

我覺得這是一個重複。檢查這個問題 - > http://stackoverflow.com/questions/6141717/next-element-in-a-associative-php-array – Nobita

回答

24
function get_next($array, $key) { 
    $currentKey = key($array); 
    while ($currentKey !== null && $currentKey != $key) { 
     next($array); 
     $currentKey = key($array); 
    } 
    return next($array); 
} 

或者:

return current(array_slice($array, array_search($key, array_keys($array)) + 1, 1)); 

這是很難,如果搜索鍵不存在與第二方法返回正確的結果。謹慎使用。

+0

我喜歡第一個解決方案!美麗。 – Nobita

+2

@Nobita @deceze不錯,但我想知道如果在$數組中找不到$ key,會發生什麼?這不會造成無限循環嗎? –

+0

@Berry好,趕上了,加了一張支票。 – deceze

-1

可以打印這樣的: -

foreach(YourArr as $key => $val) 
{ echo next(YourArr[$key]); 
    prev(YourArr); } 
+1

我不確定它可以工作。 – Karolis

+0

@Karolis可能是我寫得很快.. :) – Bajrang

0

您可以使用下一個();函數,如果你想獲得下一個即將到來的數組元素。

<?php 
$transport = array('foot', 'bike', 'car', 'plane'); 
$mode = current($transport); // $mode = 'foot'; 
$mode = next($transport); // $mode = 'bike'; 
$mode = next($transport); // $mode = 'car'; 
$mode = prev($transport); // $mode = 'bike'; 
$mode = end($transport);  // $mode = 'plane'; 
?> 

更新

,如果你想查詢和使用,下一個元素存在,您可以嘗試:

創建一個函數:

function has_next($array) { 
    if (is_array($array)) { 
     if (next($array) === false) { 
      return false; 
     } else { 
      return true; 
     } 
    } else { 
     return false; 
    } 
} 

調用它:

if (has_next($array)) { 
    echo next($array); 
} 

來源:php.net

0
$array = array("sony"=>"xperia", "apple"=>"iphone", 1 , 2, 3, 4, 5, 6); 

foreach($array as $key=>$val) 
{ 
    $curent = $val; 
    if (!isset ($next)) 
     $next = current($array); 
    else 
     $next = next($array); 
    echo (" $curent | $next <br>"); 
}