Let me tell you the basic syntax first:
array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys ]] )
array_slice() returns a sequence in the array specified by the offset and length parameters.
If offset is non-negative, the sequence will start at this offset in array. If offset is negative, the sequence will start this far from the end in the array.
If length is given and positive, there will be this many cells in the sequence. If length is given and negative, the sequence will terminate this far from the end of the array. If omitted, the sequence will start at offset and go to the end of array.
Note that array_slice() will reset the keys of the array by default. As of PHP 5.0.2, this behavior can be changed by setting preserve_keys to TRUE.
$input = array("a", "b", "c", "d", "e"); $output = array_slice($input, ); //返回下标开始的数组 returns "c", "d", and "e" $output = array_slice($input, -, ); // returns "d" $output = array_slice($input, , ); // returns "a", "b", and "c" // note the differences in the array keys print_r(array_slice($input, , -)); print_r(array_slice($input, , -, true));
If you need to return a few random pieces of data, you can first use shuffle($input); to scramble the original array, and then use array_slice to obtain it
PS: PHP array_slice() function
Definition and usage
The array_slice() function removes a segment of value from the array based on conditions and returns it.
Note: If the array has string keys, the returned array will retain the key names. (see example 4)
Grammar
Copy code The code is as follows:
array_slice(array,offset,length,preserve)
Parameters | Description |
array | Required. Specifies the input array. |
offset | Required. numerical value. Specifies the starting position of the element to be retrieved. If it is a positive number, it will be taken from front to back. If it is a negative value, it will be taken from back to front. offset Absolute value. |
length | Optional. numerical value. Specifies the length of the returned array. If length is positive, return that number of elements. 如果 length 为负,则序列将终止在距离数组末端这么远的地方。 如果省略,则序列将从 offset 开始直到 array 的末端。 |
preserve | 可选。可能的值: · true - 保留键 · false - 默认 - 重置键 |
例子 1
<?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); print_r(array_slice($a,1,2)); ?>
输出:
复制代码 代码如下:
Array ( [0] => Cat [1] => Horse )
例子 2
带有负的 offset 参数:
<?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); print_r(array_slice($a,-2,1)); ?>
输出:
复制代码 代码如下:
Array ( [0] => Horse )
例子 3
preserve 参数设置为 true:
<?php $a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird"); print_r(array_slice($a,1,2,true)); ?>
输出:
复制代码 代码如下:
Array ( [1] => Cat [2] => Horse )
例子 4
带有字符串键:
<?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse","d"=>"Bird"); print_r(array_slice($a,1,2)); ?>
输出:
复制代码 代码如下:
Array ( [b] => Cat [c] => Horse )
以上就是本文给大家介绍的php 利用array_slice函数获取数组随机或前几条数据,希望大家喜欢。