[英]Laravel - Paginate a shuffled array
I want to paginate a shuffled array of elements.我想对一个洗牌的元素数组进行分页。 I know Laravel Paginator expect a Collection.
我知道 Laravel 分页器期待一个集合。 In more details, I want to shuffle a resultset from the database.
更详细地说,我想从数据库中洗牌一个结果集。 Therefore I have the following line of code:
因此我有以下代码行:
$getallFragen = $frage->getAllFragen2()->shuffle()->all();
This line selects all questions and shuffles the collection.此行选择所有问题并打乱集合。
Furthermore I want to shuffle the answers from the questions, which also works correctly.此外,我想对问题的答案进行洗牌,这也可以正常工作。 Then I want to paginate the items with one item per page, which also works properly, but I receive duplicate items in the pagination.
然后我想用每页一个项目对项目进行分页,这也可以正常工作,但是我在分页中收到重复的项目。 First I thought, it has to be the collection, but the collection is built correctly and I don´t know, what the problem could be.
首先我想,它必须是集合,但是集合是正确构建的,我不知道问题可能是什么。 I could imagine, that my own paginator is not working the way it should.
我可以想象,我自己的分页器没有按应有的方式工作。 I also create an array, where I store the items, which are allowed in the exam and then make a collection out of the array to make sure, that there are no duplicate entries.
我还创建了一个数组,在其中存储考试中允许的项目,然后从数组中收集一个集合以确保没有重复的条目。
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$itemCollection = collect($pruefung);
$perPage = 1;
$currentPageItems = $itemCollection->slice(($currentPage * $perPage) - $perPage, $perPage)->all();
$paginatedItems = new LengthAwarePaginator($currentPageItems, count($itemCollection), $perPage);
$paginatedItems->setPath($request->url());
return view('pruefungssimulation', ["fragen" => $paginatedItems]);
In the frontend I just use @foreach($fragen as $frage)
to get all items out of the collection.在前端,我只是使用
@foreach($fragen as $frage)
从集合中取出所有项目。
I think the problem is that when you go to the next page, the collection is shuffled again.我认为问题在于,当您将 go 转到下一页时,集合再次被洗牌。
Say you have a collection [1, 2, 3]
.假设您有一个集合
[1, 2, 3]
。 When you shuffle this collection, you could get [2, 1, 3]
.当你洗牌这个集合时,你会得到
[2, 1, 3]
。 When you are on the first page, this means you see item 1.当您在第一页时,这意味着您看到了第 1 项。
When you go to the next page, the collection is shuffled again.当您 go 到下一页时,该集合再次被洗牌。 This means the collection could be the same, or could be
[1, 3, 2]
or [3, 1, 2]
.这意味着集合可以是相同的,也可以是
[1, 3, 2]
或[3, 1, 2]
。 So when you see page 2, the item you see could be item 3, item 2 or item 1 (again).因此,当您看到第 2 页时,您看到的项目可能是项目 3、项目 2 或项目 1(再次)。
If you want to keep the shuffled order, you have to save this order somewhere so it can be used every time a next/previous page is requested.如果您想保留打乱的订单,则必须将此订单保存在某处,以便每次请求下一页/上一页时都可以使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.