PHP array_chunk()
定义和用法
array_chunk() 函数把一个数组分割为新的数组块。
其中每个数组的单元数目由 size 参数决定。最后一个数组的单元数目可能会少几个。
可选参数 preserve_key 是一个布尔值,它指定新数组的元素是否有和原数组相同的键(用于关联数组),还是从 0 开始的新数字键(用于索引数组)。默认是分配新的键。
语法
array_chunk(array,size,preserve_key)
参数详解:
参数 | 描述 |
---|---|
array | 必需。规定要使用的数组。 |
size | 必需。规定每个新数组包含多少个元素。 |
preserve_key | 可选。可能的值:
|
例子 1
$arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
$arr2 = array_chunk($arr1,2,true);
$arr3 = array_chunk($arr1,2);
print_r($arr2);
print_r($arr3);
输出:
Array ( [0] => Array ( [0] => a [1] => b ) [1] => Array ( [2] => c [3] => d ) [2] => Array ( [4] => e [5] => f ) [3] => Array ( [6] => g [7] => h ) [4] => Array ( [8] => i ) ) Array ( [0] => Array ( [0] => a [1] => b ) [1] => Array ( [0] => c [1] => d ) [2] => Array ( [0] => e [1] => f ) [3] => Array ( [0] => g [1] => h ) [4] => Array ( [0] => i ) )
这两个区别主要是键值,第一个是保留原来的键值,第二个是重置了键值
例子 2
<?php $a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"Cow"); print_r(array_chunk($a,2,true)); ?>
输出:
Array ( [0] => Array ( [a] => Cat [b] => Dog ) [1] => Array ( [c] => Horse [d] => Cow ) )
例子 3
二维数组
$arr1 = [ ['a','b'], ['c','d'], ['e','f'], ['g','h'], ['i','j'] ]; $arr = array_chunk($arr1,2,true); print_r($arr1); print_r($arr);
输出:
Array ( [0] => Array ( [0] => a [1] => b ) [1] => Array ( [0] => c [1] => d ) [2] => Array ( [0] => e [1] => f ) [3] => Array ( [0] => g [1] => h ) [4] => Array ( [0] => i [1] => j ) ) Array ( [0] => Array ( [0] => Array ( [0] => a [1] => b ) [1] => Array ( [0] => c [1] => d ) ) [1] => Array ( [2] => Array ( [0] => e [1] => f ) [3] => Array ( [0] => g [1] => h ) ) [2] => Array ( [4] => Array ( [0] => i [1] => j ) ) )
说明
一共5组元素,前面每组一个元素,最后一组只有1个元素