PHP:返回数组的第一个/最后N个元素的任何功能
问题描述:
我想将过去/前N元素返回数组的功能。
I want a function that will return last/first N element of an array.
例如:
$data = array( '0','1','2','3','4','5','6','7','8','9','10' );
如果
getItems( $data, '5', 'first' );
output: array( '0','1','2','3','4' )
如果
getItems( $data, '2', 'last' );
output: array( '9','10' );
如果
getItems( $data, '11', 'first' ); or getItems( $data, '11', 'last' );
output: array( '0','1','2','3','4','5','6','7','8','9','10' );
时已经有这样的功能。如果没有,那么什么是最近的路。
Is there already a function like this. If not then what is the shortest way.
感谢
答
您正在寻找 array_slice()
(手册页的here )。
You're looking for array_slice()
(man page here).
例如:
$arr = array(1, 2, 3, 4, 5);
$slice1 = array_slice($arr, 2); //take all elements from 3rd on
$slice2 = array_slice($arr, 0, 3); //take first three elements