Laravel 4.x 分页数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23400302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:27:07  来源:igfitidea点击:

Laravel 4.x Paginate Array

arrayslaravellaravel-4paginationpaginate

提问by user2631256

For simplicities sake, I have an array, $matches, containing my results in my controller. Normally, I would return a view, passing that array along.

为简单起见,我有一个数组 $matches,其中包含我的控制器中的结果。通常,我会返回一个视图,同时传递该数组。

return View::make('results', compact('matches'));

However, I want to paginate these results in the view.

但是,我想在视图中对这些结果进行分页。

@foreach ($matches as $match)
   ...
@endforeach
// Paginate matches here!

It seems like Laravel's built in pagination won't work for arrays. I can't find any resource that shows me how to do this. Any help would be appreciated!

似乎 Laravel 的内置分页不适用于数组。我找不到任何向我展示如何执行此操作的资源。任何帮助,将不胜感激!

回答by user2631256

I ended up using the following code. You have to pass the items per page manually. $matchesis the array of data being passed to the paginator.

我最终使用了以下代码。您必须手动传递每页的项目。$matches是传递给分页器的数据数组。

$perPage = 2;
$currentPage = Input::get('page') - 1;
$pagedData = array_slice($matches, $currentPage * $perPage, $perPage);
$matches = Paginator::make($pagedData, count($matches), $perPage);

回答by Antonio Carlos Ribeiro

You can create paginators manually and they work with arrays:

您可以手动创建分页器,它们可以与数组一起使用:

$paginator = Paginator::make($items, $totalItems, $perPage);

Check the docs: http://laravel.com/docs/pagination

检查文档:http: //laravel.com/docs/pagination

回答by PerfectM

If you want to manually paginate this is the best answer. This is usefull when your query contain distinct().

如果您想手动分页,这是最好的答案。当您的查询包含 distinct() 时,这很有用。

$matches = DB::table('...')->where('...')->distict()->get();    
$perPage = 2;
$currentPage = Input::get('page', 1) - 1;
$pagedData = array_slice($matches, $currentPage * $perPage, $perPage);
$matches = Paginator::make($pagedData, count($matches), $perPage);