2010-09-15 136 views
139

完成此操作的最佳方法是什麼?獲取數組的前N個元素?

+7

如果你需要找到一個函數來做一些數組,請到這裏:http://www.php.net/manual/en/function.array.php並查看函數。 – Galen 2010-09-15 17:27:47

+12

而不是來過! – 2011-07-27 06:57:46

回答

248

使用array_slice()更快

這是從PHP manual: array_slice

$input = array("a", "b", "c", "d", "e"); 
$output = array_slice($input, 0, 3); // returns "a", "b", and "c" 
爲例

只有一個小問題

如果數組索引是有意義的你,記得array_slice將重置並重新排序數字數組索引。您需要將preserve_keys標誌設置爲true以避免這種情況。 (第4個參數,自5.0.2起可用)。

例子:

$output = array_slice($input, 2, 3, true); 

輸出:

array([3]=>'c', [4]=>'d', [5]=>'e'); 
+12

哇,3年編輯:)幹得好。 – webnoob 2014-01-27 22:05:49

11

在當前順序?我會說array_slice()。因爲它是一個內置的功能,它會比通過數組循環,同時保持遞增指數的跟蹤,直到N.

21

您可以使用array_slice爲:

$sliced_array = array_slice($array,0,$N); 
+0

這就是我完全想要的。謝謝 – 2015-10-12 11:40:07

0

array_slice()是嘗試最好的事情,以下是例子:

<?php 
$input = array("a", "b", "c", "d", "e"); 

$output = array_slice($input, 2);  // returns "c", "d", and "e" 
$output = array_slice($input, -2, 1); // returns "d" 
$output = array_slice($input, 0, 3); // returns "a", "b", and "c" 

// note the differences in the array keys 
print_r(array_slice($input, 2, -1)); 
print_r(array_slice($input, 2, -1, true)); 
?>