php数组函数array_slice、array_splice
array_slice 函数在数组中根据条件取出一段值,并返回,不影响原数组
array_splice 函数从数组中移除选定的元素,并用新元素取代它。该函数也将返回包含被移除元素的数组。
<?php $arr = [0,1,2,3,4,5,6]; $a = array_slice($arr,3,3,true);//取数组从第4个开始长度为3的元素,保留之前键值,组成新的数组返回,不影响原数组 print_r( $arr );//0,1,2,3,4,5,6 echo "<br/>"; print_r( $a );//3,4,5 echo "<br/>"; $b = [0,1,2,3,5,6]; $c = array_splice($b,1,4);//截取数组b从第2个开始长度为4的元素,组成新的数组返回,影响原数组 print_r($b);//0,6 echo "<br/>"; print_r($c);//1,2,3,5 echo "<br/>"; $b = [0,1,2,3,5,6]; $d = array_splice($b,4,0,[4]);//在数组b的第5个位置删除0个元素,并插入[4]这个数组,返回值为空,影响原数组 print_r($b);//0,1,2,3,4,5,6
print_r($d);
运行结果:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 )
Array ( [3] => 3 [4] => 4 [5] => 5 )
Array ( [0] => 0 [1] => 6 )
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 5 )
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 )
Array ( )