How to I get an array of the last n items of another array in PHP?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
$n
is equal to the number of items you want off the end.
$arr = array_slice($old_arr, -$n);
回答2:
You can use 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.
回答3:
You can use 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
.