每天一个常用PHP函数-array_chunk

场景
我们通常从db或者api中获取数组数据,然后进行处理,那如果数据太大怎么办?或者进行api请求的时候数据太大,如何分批进行,array_chunk登场了。
语法
array_chunk ( array $array , int $size [, bool $preserve_keys = FALSE ] ) : array
$array 需要处理的数组
$size 拆分后每个数组的元素数量
$preserve_keys 是否需要保证key不变
分割之后返回多维数组
使用
$userList = [
['id' => 1, 'name' => '快乐的鸟', 'totalAmount' => 1000],
['id' => 2, 'name' => '愤怒的鸟', 'totalAmount' => 10],
['id' => 3, 'name' => '忧伤的鸟', 'totalAmount' => 100],
['id' => 4, 'name' => '勤奋的鸟', 'totalAmount' => 3000],
['id' => 5, 'name' => '孤单的鸟', 'totalAmount' => 9000],
];
// 两个元素进行分割
print_r(array_chunk($userList, 2));
/**
Array
(
[0] => Array
(
[0] => Array
(
[id] => 1
[name] => 快乐的鸟
[totalAmount] => 1000
)
[1] => Array
(
[id] => 2
[name] => 愤怒的鸟
[totalAmount] => 10
)
)
[1] => Array
(
[0] => Array
(
[id] => 3
[name] => 忧伤的鸟
[totalAmount] => 100
)
[1] => Array
(
[id] => 4
[name] => 勤奋的鸟
[totalAmount] => 3000
)
)
[2] => Array
(
[0] => Array
(
[id] => 5
[name] => 孤单的鸟
[totalAmount] => 9000
)
)
)
**/
上面默认preserve_keys为false, 如果设置为true, 则新数组中的元素仍保持原数组中的索引index
print_r(array_chunk($userList, 2, true));
/**
Array
(
[0] => Array
(
[0] => Array
(
[id] => 1
[name] => 快乐的鸟
[totalAmount] => 1000
)
[1] => Array
(
[id] => 2
[name] => 愤怒的鸟
[totalAmount] => 10
)
)
[1] => Array
(
[2] => Array
(
[id] => 3
[name] => 忧伤的鸟
[totalAmount] => 100
)
[3] => Array
(
[id] => 4
[name] => 勤奋的鸟
[totalAmount] => 3000
)
)
[2] => Array
(
[4] => Array
(
[id] => 5
[name] => 孤单的鸟
[totalAmount] => 9000
)
)
)
**/
相关推荐
-
MySQL 中的反斜杠 \\,真是太坑了2025-04-21 01:42:45
-
mysql修改主键为自增 ,如果自增达到最大值,新增加数据会怎样?
mysql修改主键为自增 ,如果自增达到最大值,新增加数据会怎样?2025-04-21 01:31:46 -
Nginx学习笔记 autoindex on2025-04-21 00:26:47
-
.MySQL中的BETWEEN(在某个范围)2025-04-21 00:04:20
-
nginx设置目录浏览并支持中文2025-04-21 00:00:35