2012-12-10 52 views
1

我想告訴我的數組從鍵位置2開始,然後遍歷整個數組,包括鍵位置2之前的值。我只想使用一個數組並指定鍵我從頭開始循環。例如,在這裏我使用的是array_splice,但它沒有做到我想要的,你能幫助我嗎?PHP使陣列從鍵/位置開始

$names = array('Bill', 'Ben', 'Bert', 'Ernie'); 
foreach(array_slice($names, 2) as $name){ 
    echo $name; 
} 

foreach(array_slice($names, 3) as $name){ 
    echo $name; 
} 
+0

所以你不想使用'foreach'而是'for' –

回答

3

如果密鑰是不相關的,可以拼接數組兩次,合併產生的陣列,像這樣:

$names = array('Bill', 'Ben', 'Bert', 'Ernie'); 
$start = 2; 

foreach(array_merge(array_slice($names, $start), array_slice($names, 0, $start)) as $name){ 
    echo $name; 
} 

您可以從the demo看到這個打印:

BertErnieBillBen 

另外,爲了提高效率,您可以使用兩個知道封裝到開頭的循環,由於您使用原始陣列進行操作,效率會更高並且不創建它的副本。

$start = 2; 
for($i = $start, $count = count($names); $i < $count; $i++) { 
    echo $names[$i]; 
} 
$i = 0; 
while($i < $start) { 
    echo $names[$i++]; 
} 

你也可以把它變成一個單迴路,只是封裝邏輯爲for內纏繞。

+0

這是現貨,謝謝! :) –

0
$limit = 2; //so you can set your start index to an arbitrary number 
$fn= function($a,$b) use ($limit){ 
    if(($a < $limit && $b < $limit) 
     || ($a >= $limit && $b >=$limit)) //$a and $b on the same side of $limit 
     return $a < $b ? -1 : ($a==$b ? 0 : 1); 
    if($a < $limit && $b > $limit) return 1; //because $a will always be considered greater 
    if($a >= $limit && $b < $limit) return -1; //because $b will always be considered greater 

}; 
uksort($arr, $fn); 
foreach($arr as $v) echo $v;