我目前正在使用 Laravel 5.6,并且我有一个 api 的结果。我正在尝试对结果进行分页,但无法做到。
\n\n我的json结果是这样的:
\n\n{#922 \xe2\x96\xbc\n +"orders": array:50 [\xe2\x96\xbc\n 0 => {#220 \xe2\x96\xb6}\n 1 => {#234 \xe2\x96\xb6}\n 2 => {#250 \xe2\x96\xb6}\n 3 => {#263 \xe2\x96\xb6}\n 4 => {#274 \xe2\x96\xb6}\n 5 => {#297 \xe2\x96\xb6}\n 6 => {#310 \xe2\x96\xb6}\n 7 => {#322 \xe2\x96\xb6}\n 8 => {#338 \xe2\x96\xb6}\n 9 => {#351 \xe2\x96\xb6}\n ]\n}\nRun Code Online (Sandbox Code Playgroud)\n\n然后我收到订单并将其放入变量中,如下所示:$orders = $call->orders;
我已经尝试过这样做:
\n\n$orders = $shopifyData->paginate(20)->toArray();\nRun Code Online (Sandbox Code Playgroud)\n\n我收到此错误:\n调用数组上的成员函数 paginate()
\n\n我也尝试过这个: $orders::Paginate(20);\n也不起作用。
我想我错过了如何做到这一点的第一步,但老实说我迷路了。我不太确定该怎么做。谷歌搜索有几个关于如何使用 Eloquent 模型从数据库检索数据时执行此操作的示例。它还展示了当您查询数据库但什么也不做时如何执行此操作。Laravel 文档在 5.6 分页下找到:\nPaginating Query Builder Results\nPaginating Eloquent Results
\n\n\n\n\n\n\n\n\n手动创建分页器\n非常有限,只说使用分页器或lengthAwarePginator并使用array_slice。
\n
有人能指出我如何实现这一目标的正确方向吗?
\n我假设您正在尝试以 Laravel 方式对普通的 PHP 数组进行分页。
该paginate函数仅适用于查询构建器,因此不适用于数组。要执行您想要的操作,您首先需要知道用户正在查看哪个页面。通常,当前页面是通过pageGET 参数传递的,但 LaravelLengthAwarePaginator提供了提取该参数的功能。您将需要一个use才能使其工作。
use Illuminate\Pagination\LengthAwarePaginator; // don't forget to add this
....
$current_page = LengthAwarePaginator::resolveCurrentPage();
Run Code Online (Sandbox Code Playgroud)
然后您需要slice包含结果的数组。相应地设置$perPage变量。那么你要么需要:
将你的数组变成 aCollection并且slice它
$orders = $call->orders;
$orders_collection = new Collection($orders); // needs a use statement
$orders_collection = collect($orders); // alternative. You can use helper function
$current_page_orders = $orders_collection->slice(($current_page - 1) * $perPage, $perPage)->all(); // slice($offset, $number_of_item)
Run Code Online (Sandbox Code Playgroud)或直接用于array_slice您的阵列。
$orders = $call->orders;
$current_page_orders = array_slice($orders, ($current_page - 1) * $perPage, $perPage);
Run Code Online (Sandbox Code Playgroud)$current_page_orders仍然是(切片)Collection或array,所以让我们创建一个分页器实例。
$orders_to_show = new LengthAwarePaginator($current_page_orders, count($orders_collection), $perPage);
Run Code Online (Sandbox Code Playgroud)
$orders_to_show现在是您想要的分页结果。您应该能够像处理数据库中的分页结果一样使用它。
| 归档时间: |
|
| 查看次数: |
3864 次 |
| 最近记录: |