好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

php array_slice() 函数

PHP array_slice() 函数

PHP Array 函数

定义和用法: array_slice() 函数在数组中根据条件取出一段值,并返回.

注释: 如果数组有字符串键,所返回的数组将保留键名,参见例子 4.

语法: array_slice(array,offset,length,preserve)

参数 描述 

array 必需,规定输入的数组.

offset 必需,数值,规定取出元素的开始位置,如果是正数,则从前往后开始取,如果是负值,从后向前取 offset 绝对值.

length 可选,数值,规定被返回数组的长度,如果是负数,则从后向前,选取该值绝对值数目的元素,如果未设置该值,则返回所有元素.

preserve 可选,可能的值:true - 保留键,false - 默认 - 重置键.

PHP实例代码如下:

<?php   /*    用手册上的例子    */    $input  =  array  ( "a" ,  "b" ,  "c" ,  "d" ,  "e" );   $output  =  array_slice  ( $input , 2);  // returns "c", "d", and "e",    $output  =  array_slice  ( $input , 2, -1);  // returns "c", "d"    $output  =  array_slice  ( $input , -2, 1);  // returns "d"    $output  =  array_slice  ( $input , 0, 3);  // returns "a", "b", and "c"    ?> 

实例:

<?php  $term  =  $_REQUEST [ 'q' ];  $images  =  array_slice (scandir( "images" ), 2);  foreach ( $images   as   $value ) {    if (  strpos ( strtolower ( $value ),  $term ) === 0 ) {     echo   $value  .  " " ;   }  }  ?>    <?php   // split the given array into n number of pieces    function  array_split( $array ,  $pieces =2)   {          if  ( $pieces  < 2)            return   array ( $array );        $newCount  =  ceil ( count ( $array )/ $pieces );        $a  =  array_slice ( $array , 0,  $newCount );        $b  = array_split( array_slice ( $array ,  $newCount ),  $pieces -1);        return   array_merge ( array ( $a ), $b );   }    // Examples:    $a  =  array (1,2,3,4,5,6,7,8,9,10);   array_split( $a , 2);     // array(array(1,2,3,4,5), array(6,7,8,9,10))    array_split( $a , 3);     // array(array(1,2,3,4), array(5,6,7), array     (8,9,10))   array_split( $a , 4);     // array(array(1,2,3), array(4,5,6), array(7,8),   //开源代码phpfensi测试数据   array (9,10))    ?>  

查看更多关于php array_slice() 函数的详细内容...

  阅读:44次