PHP array_chunk() 函数可以将一个数组分割成多个,其语法如下:
参数说明:
array_chunk() 会将 arr 数组分割成多个子数组,每个子数组的元素个数由 size 决定。最后一个子数组的元素个数可能会少于 size 个。
返回值:返回一个由分割后的子数组构成的多维数组。
使用示例如下:
<?php
$arr1 = array("城东书院", "PHP教程", "http://www.cdsy.xyz/computer/programme/PHP/", "Java教程", "http://www.cdsy.xyz/computer/programme/java/", "Python教程", "http://www.cdsy.xyz/computer/programme/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, 3, true) );
?>
执行以上程序的输出结果如下:
Array
(
[0] => Array
(
[0] => 城东书院
[1] => PHP教程
[2] => http://www.cdsy.xyz/computer/programme/PHP/
)
[1] => Array
(
[0] => Java教程
[1] => http://www.cdsy.xyz/computer/programme/java/
[2] => Python教程
)
[2] => Array
(
[0] => http://www.cdsy.xyz/computer/programme/python/
)
)
Array
(
[0] => Array
(
[0] => 城东书院
[1] => PHP教程
[2] => http://www.cdsy.xyz/computer/programme/PHP/
)
[1] => Array
(
[3] => Java教程
[4] => http://www.cdsy.xyz/computer/programme/java/
[5] => Python教程
)
[2] => Array
(
[6] => http://www.cdsy.xyz/computer/programme/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
)
)