我目前使用的是 Laravel 5.6,并且我有一个 api 的结果。我正在尝试对结果进行分页,但无法做到。
我的json结果是这样的:
{#922 ▼
+"orders": array:50 [▼
0 => {#220 ▶}
1 => {#234 ▶}
2 => {#250 ▶}
3 => {#263 ▶}
4 => {#274 ▶}
5 => {#297 ▶}
6 => {#310 ▶}
7 => {#322 ▶}
8 => {#338 ▶}
9 => {#351 ▶}
]
}
然后我获取订单并将其放入变量中,如下所示:$orders = $call->orders;
我已经尝试过:
$orders = $shopifyData->paginate(20)->toArray();
我收到此错误: 调用数组上的成员函数 paginate()
我也尝试过这个:$orders::Paginate(20);
也不起作用。
我想我错过了如何做到这一点的第一步,但老实说我迷路了。我不太确定该怎么做。谷歌搜索有几个关于如何使用 Eloquent 模型从数据库检索数据时执行此操作的示例。它还展示了当您查询数据库但什么也不做时如何执行此操作。 5.6分页下找到的laravel文档: 对查询生成器结果进行分页 对 Eloquent 结果进行分页
block 引用> block 引用>Manually Creating A Paginator is very limited and only says to use paginator or lengthAwarePginator and to use array_slice.
有人能指出我如何实现这一目标的正确方向吗?
最佳答案
我假设您正在尝试以 Laravel 方式对普通的 PHP 数组进行分页。
paginate
函数仅适用于查询构建器,因此它不适用于数组。
要执行您想要的操作,您首先需要知道用户正在查看哪个页面。通常,当前页面是通过 page
GET 参数传递的,但 Laravel 的 LengthAwarePaginator
提供了提取该页面的功能。您需要使用
才能使其工作。
use Illuminate\Pagination\LengthAwarePaginator; // don't forget to add this
....
$current_page = LengthAwarePaginator::resolveCurrentPage();
然后您需要对包含结果的数组进行切片
。相应地设置 $perPage
变量。那么你要么需要:
将数组转换为
集合
并对其进行切片
$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)
或直接对数组使用
array_slice
。$orders = $call->orders; $current_page_orders = array_slice($orders, ($current_page - 1) * $perPage, $perPage);
$current_page_orders
仍然是一个(切片的)Collection
或 array
,所以让我们创建一个分页器实例。
$orders_to_show = new LengthAwarePaginator($current_page_orders, count($orders_collection), $perPage);
$orders_to_show
现在是您想要的分页结果。您应该能够像处理数据库中的分页结果一样使用它。
关于laravel-5 - Laravel 中的 json 数组分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50123423/