📅  最后修改于: 2023-12-03 15:32:36.911000             🧑  作者: Mango
Laravel 集合是对 PHP 原生数组的一个扩展,提供了更为便捷的数组操作方法。其中,forPage 方法可以实现对数组按页查询。
$collection->forPage($page, $perPage);
$page
: 要返回的页数。$perPage
: 每页显示的数目。$users = collect([
['id' => 1, 'name' => '小明'],
['id' => 2, 'name' => '小黄'],
['id' => 3, 'name' => '小花'],
['id' => 4, 'name' => '小红'],
['id' => 5, 'name' => '小绿'],
['id' => 6, 'name' => '小紫'],
]);
$page1 = $users->forPage(1, 2);
/*
$page1 = [
['id' => 1, 'name' => '小明'],
['id' => 2, 'name' => '小黄'],
];
*/
$page2 = $users->forPage(2, 2);
/*
$page2 = [
['id' => 3, 'name' => '小花'],
['id' => 4, 'name' => '小红'],
];
*/
forPage
方法支持链式调用,如:
$users = collect([
['id' => 1, 'name' => '小明'],
['id' => 2, 'name' => '小黄'],
['id' => 3, 'name' => '小花'],
['id' => 4, 'name' => '小红'],
['id' => 5, 'name' => '小绿'],
['id' => 6, 'name' => '小紫'],
]);
$firstTwo = $users->sortBy('id')->forPage(1, 2);
/*
$firstTwo = [
['id' => 1, 'name' => '小明'],
['id' => 2, 'name' => '小黄'],
];
*/
$lastTwo = $users->sortBy('id')->forPage(2, 2);
/*
$lastTwo = [
['id' => 3, 'name' => '小花'],
['id' => 4, 'name' => '小红'],
];
*/
使用 forPage
方法,可以轻松实现对数组分页查询的操作,例如用于实现用户列表分页,或查询大量数据时进行分批处理。