把数组分割为带有两个元素的数组块:
$cars = ['Volvo', 'BMW', 'Toyota', 'Honda', 'Mercedes', 'Opel'];
dump(array_chunk($cars, 2));
array(3) {
[0] => array(2) {
[0] => string(5) "Volvo"
[1] => string(3) "BMW"
}
[1] => array(2) {
[0] => string(6) "Toyota"
[1] => string(5) "Honda"
}
[2] => array(2) {
[0] => string(8) "Mercedes"
[1] => string(4) "Opel"
}
}
array_chunk() 函数把一个数组分割为新的数组块。
array_chunk(array,size,preserve_keys);
参数 | 描述 |
---|---|
array | 必需。规定要使用的数组。 |
size | 必需。一个整数,规定每个新数组块包含多少个元素。 |
preserve_key | 可选。可能的值:
|
返回值: | 返回一个多维的数值数组,从 0 开始,每个维度都包含 size 元素。 |
---|---|
PHP 版本: | 4.2+ |
数组中的元素数量不能被size整除
$cars = ['Volvo', 'BMW', 'Toyota', 'Honda', 'Mercedes'];
dump(array_chunk($cars, 2));
array(3) {
[0] => array(2) {
[0] => string(5) "Volvo"
[1] => string(3) "BMW"
}
[1] => array(2) {
[0] => string(6) "Toyota"
[1] => string(5) "Honda"
}
[2] => array(1) {
[0] => string(8) "Mercedes"
}
}
size的值大于数组中元素的数量
$cars = ['Volvo', 'BMW', 'Toyota', 'Honda', 'Mercedes', 'Opel'];
dump(array_chunk($cars, 10));
array(1) {
[0] => array(6) {
[0] => string(5) "Volvo"
[1] => string(3) "BMW"
[2] => string(6) "Toyota"
[3] => string(5) "Honda"
[4] => string(8) "Mercedes"
[5] => string(4) "Opel"
}
}
保留原数组的键名
$cars = ['Volvo', 'BMW', 'Toyota', 'Honda', 'Mercedes', 'Opel'];
dump(array_chunk($cars, 3, true));
array(2) {
[0] => array(3) {
[0] => string(5) "Volvo"
[1] => string(3) "BMW"
[2] => string(6) "Toyota"
}
[1] => array(3) {
[3] => string(5) "Honda"
[4] => string(8) "Mercedes"
[5] => string(4) "Opel"
}
}
2023-07-25 更新 本文链接:https://upwqy.com/wiki/info/437.html