版权声明:欢迎转评,一起学习. https://blog.csdn.net/xiaobinqt/article/details/85102464
在使用 Laravel 时,除了在 ORM 中使用分页外,有些时候也需要对用原生 sql 查询的数据进行分页,该查询数据可能是数组,也可能是对象数组.
支持数组格式:
$goods = [
[],[],[]
];
数组对象格式:
以下封装了一个方法可供使用
if (!function_exists("page_with_array")){
function page_with_array($request,$array_item){
$currentPage = \Illuminate\Pagination\LengthAwarePaginator::resolveCurrentPage();
$itemCollection = collect($array_item);
$perPage = env('PAGE_SIZE'); // 每页数量
$currentPageItems = $itemCollection->slice(($currentPage*$perPage)-$perPage,$perPage)->all();
$paginatedItems = new \Illuminate\Pagination\LengthAwarePaginator($currentPageItems,count($itemCollection),$perPage);
return $paginatedItems->setPath($request->url());
}
}
测试结果
参考: