php从数组中取出一段 之 array_slice


array array_slice ( array $array , int $offset [, int $length [, bool $preserve_keys ]] )

array_slice() 返回根据 offset 和 length 参数所指定的 array 数组中的一段序列。

如果 offset 非负,则序列将从 array 中的此偏移量开始。如果 offset 为负,则序列将从 array 中距离末端这么远的地方开始。

如果给出了 length 并且为正,则序列中将具有这么多的单元。如果给出了 length 并且为负,则序列将终止在距离数组末端这么远的地方。如果省略,则序列将从 offset 开始一直到 array 的末端。

 

array_slice($array ,2 ,3)此段代码表示从$array数组中从第二个开始,取三个值;

array_slice($array ,3)此时代码表示从$array数组中第三个之后的所有数组。

array_slice() 例子

[php] view plain copy
<?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 "d"  
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"  
  
// note the differences in the array keys  
print_r(array_slice($input, 2, -1));  
print_r(array_slice($input, 2, -1, true));  
?>  

  

<?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 "d"  
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"  
  
// note the differences in the array keys  
print_r(array_slice($input, 2, -1));  
print_r(array_slice($input, 2, -1, true));  
?>  

  输出结果

Array  
(  
    [0] => c  
    [1] => d  
)  
Array  
(  
    [2] => c  
    [3] => d  
)  

  

Array  
(  
    [0] => c  
    [1] => d  
)  
Array  
(  
    [2] => c  
    [3] => d  
)  

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM