php 获取数组的前 N ​​个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3720096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:51:25  来源:igfitidea点击:

Get the first N elements of an array?

phparrays

提问by GSto

What is the best way to accomplish this?

实现这一目标的最佳方法是什么?

回答by corbacho

Use array_slice()

使用array_slice()

This is an example from the PHP manual: array_slice

这是PHP 手册中的一个示例:array_slice

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

There is only a small issue

只有一个小问题

If the array indices are meaningful to you, remember that array_slicewill reset and reorder the numericarray indices. You need the preserve_keysflag set to trueto avoid this. (4th parameter, available since 5.0.2).

如果数组索引对您有意义,请记住这array_slice将重置并重新排序数字数组索引。您需要设置preserve_keys标志true来避免这种情况。(第四个参数,从 5.0.2 开始可用)。

Example:

例子:

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

Output:

输出:

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

回答by codaddict

You can use array_sliceas:

您可以将array_slice用作:

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

回答by Fanis Hatzidakis

In the current order? I'd say array_slice(). Since it's a built in function it will be faster than looping through the array while keeping track of an incrementing index until N.

按当前顺序?我会说array_slice()。因为它是一个内置函数,所以它比循环遍历数组要快,同时跟踪一个递增的索引直到 N。

回答by Star

array_slice()is best thing to try, following are the examples:

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));
?>

回答by Alon Gouldman

if you want to get the first N elements and alsoremove it from the array, you can use array_splice()(note the 'p' in "splice"):

如果您想获取前 N 个元素并将其从数组中删除,您可以使用array_splice()(注意“拼接”中的“p”):

http://docs.php.net/manual/da/function.array-splice.php

http://docs.php.net/manual/da/function.array-splice.php

use it like so: $array_without_n_elements = array_splice($old_array, 0, N)

像这样使用它: $array_without_n_elements = array_splice($old_array, 0, N)