array_chunk() 是 PHP 內建函數,將陣列切割成指定大小的區塊陣列,極適合分頁顯示、批次匯入、平行處理等場景。
array_chunk(array $array, int $length, bool $preserve_keys = false): array
$length:每區塊元素數 (正整數)。$preserve_keys:true 保留原鍵名 (關聯陣列適用),false (預設) 重新索引 0 起始。<?php
$teams = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// 每 2 個一組,重新索引
$chunks = array_chunk($teams, 2);
print_r($chunks);
/*
Array
(
[0] => Array ( [0] => 1, [1] => 2 )
[1] => Array ( [0] => 3, [1] => 4 )
[2] => Array ( [0] => 5, [1] => 6 )
[3] => Array ( [0] => 7, [1] => 8 )
[4] => Array ( [0] => 9 ) // 最後一組不足 2 個
)
*/
// 保留原鍵名 (關聯陣列)
$assoc = ['a'=>1, 'b'=>2, 'c'=>3, 'd'=>4];
print_r(array_chunk($assoc, 2, true));
/*
Array
(
[0] => Array ( [a] => 1, [b] => 2 )
[1] => Array ( [c] => 3, [d] => 4 )
)
*/
?>
<?php
$items = range(1, 100); // 100 筆資料
$page = (int)($_GET['page'] ?? 1);
$perPage = 10;
$pages = array_chunk($items, $perPage);
$totalPages = count($pages);
$currentPageData = $pages[$page - 1] ?? [];
echo "第 {$page} 頁 / 共 {$totalPages} 頁
";
foreach ($currentPageData as $item) {
echo "項目 {$item}
";
}
?>
<?php
$records = [/* 10000 筆資料 */];
$batches = array_chunk($records, 500); // 每批 500 筆
foreach ($batches as $batch) {
$placeholders = implode(',', array_fill(0, count($batch), '(?,?,?)'));
$sql = "INSERT INTO logs (type, msg, time) VALUES {$placeholders}";
$params = [];
foreach ($batch as $row) $params = array_merge($params, $row);
$pdo->prepare($sql)->execute($params);
}
?>
<?php
$tasks = [/* 大量任務 */];
$workerCount = 4;
$chunks = array_chunk($tasks, ceil(count($tasks) / $workerCount));
foreach ($chunks as $i => $chunk) {
$pid = pcntl_fork();
if ($pid === -1) { die('fork 失敗'); }
if ($pid === 0) {
// 子進程處理 $chunk
foreach ($chunk as $task) { process($task); }
exit(0);
}
}
// 父進程等待
while (pcntl_waitpid(0, $status) != -1) {}
?>
<?php
$userData = [
'user_1' => ['name'=>'Alice', 'age'=>25],
'user_2' => ['name'=>'Bob', 'age'=>30],
'user_3' => ['name'=>'Carol', 'age'=>28],
'user_4' => ['name'=>'Dave', 'age'=>35],
];
$groups = array_chunk($userData, 2, true);
// 保留 user_1, user_2... 鍵名,方便後續更新/刪除
?>
| 函數 | 用途 | 鍵名處理 |
|---|---|---|
array_chunk | 切割成固定大小區塊 | 可選保留 |
array_slice | 切片 (指定起始/長度) | 可選保留 |
array_splice | 移除並可替換 (修改原陣列) | 重新索引 |
array_split | 不存在 (常誤寫) | - |
array_chunk 會建立新陣列複製資料,大陣列 (10萬+) 會佔用雙倍記憶體。串流處理考慮 Generator 分塊產生。preserve_keys=true 稍慢,僅關聯陣列必要時啟用。