当前位置: 首页 > 网络学院 > 服务端脚本教程 > PHP > array_slice() 函数

PHP
PHP Libxml
PHP Math
PHP Misc
PHP MySQL
PHP SimpleXML
PHP String
PHP XML
PHP Zip
PHP Mail
用PHP5的DirectoryIterators递归扫描目录
PHP 阻止SQL注入式攻击
PHP5面向对象 - 基础 - 类和对象
PHP5面向对象 - 基础 - 类的属性( public )
PHP5面向对象 - 基础 - 类的属性( private )
PHP5面向对象 - 基础 - 方法
PHP5面向对象 - 基础 - 对象的比较
php5面向对象 - 基础 - 构造函数
php5面向对象 - 基础 - 析构函数
用PHP控制用户的浏览器 - ob*函数的使用
PHP PDO 学习笔记

PHP 中的 array_slice() 函数


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-03-04   浏览: 442 ::
收藏到网摘: n/a

Definition and Usage
定义和用法

The array_slice() function returns selected parts of an array.
array_slice()函数的作用是:返回一个数组中指定的元素。

Syntax
语法

array_slice(array,start,length,preserve)

Parameter参数 Description描述
array Required. Specifies an array
必要参数。指定一个数组
start Required. Numeric value. Specifies where the function will start the slice. 0 = the first element. If this value is set to a negative number, the function will start slicing that far from the last element. -2 means start at the second last element of the array.
必要参数。数值。指定需要返回的元素在数组中的位置。0表示第一个元素。如果设定的值是一个负数,那么表示返回的起始元素从数组的最后位置开始算起。-2表示数组中的倒数第二个元素。
length Optional. Numeric value. Specifies the length of the returned array. If this value is set to a negative number, the function will stop slicing that far from the last element. If this value is not set, the function will return all elements, starting from the position set by the start-parameter.
可选参数。数值型。指定需要返回的数组长度(即:以起始元素为基准从前往后数[长度数量包括起始元素])。如果这个值为负数,那么返回的长度是从起始元素开始往前返回的数量(即:以起始元素为基准从后往前数[长度数量包括起始元素]);如果这个指没有被设置,那么函数将从start参数设置的起始位置开始返回所有参数
preserve Optional. Possible values:
可选参数。下面列举可以使用的值:
  • true -  Preserve keys
    真true – 保留原来的键
  • false - Default - Reset keys
    假false – 默认值 – 重新设置键



Tips and Notes
注意点

Note: If the array have string keys, the returned array will allways preserve the keys. (See example 4)
注意:如果数组包含字符型键,那么将保留这些键。(见案例4)


Example 1
案例1

<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,1,2));
?>

The output of the code above will be:
上述代码将输出下面的结果:

Array ( [0] => Cat [1] => Horse )


Example 2
案例2

With a negative start parameter:
Start参数为负数的情况:

<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,-2,1));
?>

The output of the code above will be:
上述代码将输出下面的结果:

Array ( [0] => Horse )


Example 3
案例3

With the preserve parameter set to true:
Preserve参数的值设置为true的情况:

<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,1,2,true));
?>

The output of the code above will be:
上述代码将输出下面的结果:

Array ( [1] => Cat [2] => Horse )


Example 4
案例4

With string keys:
包含字符串键的情况:

<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse","d"=>"Bird");
print_r(array_slice($a,1,2));
?>

The output of the code above will be:
上述代码将输出下面的结果:

Array ( [b] => Cat [c] => Horse )

评论 (0) All

登陆 | 还没注册?