array_slice() - 从数组中取出一段 - php 数组函数
array_slice()
(PHP 4, PHP 5, PHP 7)
从数组中取出一段
说明
array_slice(array $array,int $offset[,int $length=NULL[,bool $preserve_keys= false]]): arrayarray_slice()返回根据$offset和$length参数所指定的$array数组中的一段序列。
参数
$array输入的数组。
如果$offset非负,则序列将从$array中的此偏移量开始。如果$offset为负,则序列将从$array中距离末端这么远的地方开始。
$length如果给出了$length并且为正,则序列中将具有这么多的单元。如果给出了$length并且为负,则序列将终止在距离数组末端这么远的地方。如果省略,则序列将从$offset开始一直到$array的末端。
$preserve_keys注意array_slice()默认会重新排序并重置数组的数字索引。你可以通过将$preserve_keys设为TRUE
来改变此行为。
返回值
返回其中一段。如果 offset 参数大于 array 尺寸,就会返回空的 array。
更新日志
版本 | 说明 |
---|---|
5.2.4 | $length参数默认值改成NULL。现在$length为NULL时,意思是说使用$array的长度。之前的版本里,NULL的$length的意思是长度为零(啥也不返回)。 |
5.0.2 | 增加了可选参数$preserve_keys。 |
范例
Example #1array_slice()例子
以上例程会输出:
Array ( [0] => c [1] => d ) Array ( [2] => c [3] => d )
参见
array_splice()
去掉数组中的某一部分并用其它值取代unset()
释放给定的变量array_chunk()
将一个数组分割成多个
Array slice function that works with associative arrays (keys): function array_slice_assoc($array,$keys) { return array_intersect_key($array,array_flip($keys)); }
array_slice can be used to remove elements from an array but it's pretty simple to use a custom function. One day array_remove() might become part of PHP and will likely be a reserved function name, hence the unobvious choice for this function's names. (remove 9's in email)
I was trying to find a good way to find the previous several and next several results from an array created in a MySQL query. I found that most MySQL solutions to this problem were complex. Here is a simple function that returns the previous and next rows from the array.
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)