array array_chunk ( array $arr,int $size [,bool $preserve_keys = false ] )
参数说明:- arr 表示要分割的数组;
- size 表示分割后的子数组的元素个数;
- preserve_keys 表示是否保留 arr 数组中原有的键名,默认为 false,也就是不保留,分割后的每个子数组将使用从 0 开始的新的数字索引;如果设置为 true,那就保留 arr 中原有的键名。
array_chunk() 会将 arr 数组分割成多个子数组,每个子数组的元素个数由 size 决定。最后一个子数组的元素个数可能会少于 size 个。
返回值:返回一个由分割后的子数组构成的多维数组。
使用示例如下:
<?PHP $arr1 = array("C语言中文网","PHP教程","http://c.biancheng.net/PHP/","Java教程","http://c.biancheng.net/java/","Python教程","http://c.biancheng.net/python/"); print_r( array_chunk($arr1,3) ); //不保留原有键名 print_r( array_chunk($arr1,3,true) ); //保留原有键名 $arr2 = array( 'fruits'=>array('Apple','banana','pear','orange'),'animal','vehicle','architecture','food'); print_r( array_chunk($arr2,3) ); print_r( array_chunk($arr2,true) ); ?>执行以上程序的输出结果如下:
Array
(
[0] => Array
(
[0] => C语言中文网
[1] => PHP教程
[2] => http://c.biancheng.net/PHP/
)
[1] => Array
(
[0] => Java教程
[1] => http://c.biancheng.net/java/
[2] => Python教程
)
[2] => Array
(
[0] => http://c.biancheng.net/python/
)
)
Array
(
[0] => Array
(
[0] => C语言中文网
[1] => PHP教程
[2] => http://c.biancheng.net/PHP/
)
[1] => Array
(
[3] => Java教程
[4] => http://c.biancheng.net/java/
[5] => Python教程
)
[2] => Array
(
[6] => http://c.biancheng.net/python/
)
)
Array
(
[0] => Array
(
[0] => Array
(
[0] => Apple
[1] => banana
[2] => pear
[3] => orange
)
[1] => animal
[2] => vehicle
)
[1] => Array
(
[0] => architecture
[1] => food
)
)
Array
(
[0] => Array
(
[fruits] => Array
(
[0] => Apple
[1] => banana
[2] => pear
[3] => orange
)
[0] => animal
[1] => vehicle
)
[1] => Array
(
[2] => architecture
[3] => food
)
)