2013-01-04 92 views
1

可能重複:
how to skip elements in foreach loop的foreach輸出兩個陣列跳過第一

我有以下的foreach:

foreach($documents as $document): 
    print_r($document); 
endforeach; 

哪個輸出以下:

Array 
(
    [num] => 2 
) 
Array 
(
    [0] => Array 
     (
      [name] => Batman 
      [url] => http://batman.com 
     ) 

    [1] => Array 
     (
      [name] => Superman 
      [url] => http://superman.com 
     ) 

) 

第一個數組conatining [num] => 2,打印結果時我不想在我的foreach中使用。

但是,我如何擺脫該數組,所以它不會打印時,我使用寫print_r($文檔)?

回答

1

foreach讓你可以使用continue

$first = true; 

foreach($documents as $document) { 
    if($first) { 
     $first = false; 
     continue; 
    } 

    print_r($document); 
} 
+0

感謝所有的答案。這最符合我的目的。 – JohnSmith

3

使用帶有遞增索引說明符的standard for loop並跳過第一個元素。

for($i = 1; $i < count($documents); $i++) { 
    print_r($documents[i]); 
} 
0

最簡單的方法是完全刪除第一個數組,但我的猜測是你不能這樣做。不用擔心 - 這應該有你覆蓋:

for($i = 1; $i < count($documents); $i++): 
    print_r($documents[$i]); 
endfor; 

編輯:我已經創建a test case for you on Codepad.org