如何将PHP数组中的最后n项作为另一个数组?

时间:2022-10-24 17:18:32

How to I get an array of the last n items of another array in PHP?

如何获得PHP中另一个数组的最后n项的数组?

3 个解决方案

#1


41  

$n is equal to the number of items you want off the end.

$n等于你想要结束的项目的数量。

$arr = array_slice($old_arr, -$n);

#2


4  

You can use array_slice:

您可以使用array_slice:

$arr = array_slice($old_arr, -$n, $n, true);

If the array indices are meaningful to you, remember that array_slice will reset and reorder the numeric array indices. You need the preserve_keys flag (4th parameter) set to true to avoid this.

如果数组索引对您有意义,请记住array_slice将重置和重新排序数值数组索引。您需要将preserve_keys标记(第4个参数)设置为true,以避免出现这种情况。

#3


-2  

You can use http://us2.php.net/array_slice.

您可以使用http://us2.php.net/array_slice。

$new = array_slice($old, $n);

However, $n is the offset to start the slice, so to calculate it, you would need to subtract this from the length of the array: $n = count($old) - $target_size.

但是,$n是开始切片的偏移量,因此要计算它,需要从数组的长度中减去它:$n = count($old) - $target_size。

#1


41  

$n is equal to the number of items you want off the end.

$n等于你想要结束的项目的数量。

$arr = array_slice($old_arr, -$n);

#2


4  

You can use array_slice:

您可以使用array_slice:

$arr = array_slice($old_arr, -$n, $n, true);

If the array indices are meaningful to you, remember that array_slice will reset and reorder the numeric array indices. You need the preserve_keys flag (4th parameter) set to true to avoid this.

如果数组索引对您有意义,请记住array_slice将重置和重新排序数值数组索引。您需要将preserve_keys标记(第4个参数)设置为true,以避免出现这种情况。

#3


-2  

You can use http://us2.php.net/array_slice.

您可以使用http://us2.php.net/array_slice。

$new = array_slice($old, $n);

However, $n is the offset to start the slice, so to calculate it, you would need to subtract this from the length of the array: $n = count($old) - $target_size.

但是,$n是开始切片的偏移量,因此要计算它,需要从数组的长度中减去它:$n = count($old) - $target_size。