我从LengthAwarePaginator返回JSON,但JSON的data
属性不是数组。我需要它成为一个数组。有什么想法吗?
// grab query parameters
$pageNumber = $request->input('page');
$pageSize = $request->input('pageSize');
// if query params do not exist call with defaults
if(!$pageNumber) {
$pageNumber = 1;
}
if(!$pageSize) {
$pageSize = 5;
}
$offset = ($pageNumber * $pageSize) - $pageSize;
// slice full array data based on page number and page size
$itemsForCurrentPage = array_slice($arrayOfData, $offset, $pageSize, true);
return new LengthAwarePaginator($itemsForCurrentPage, count($this->orgUsers), $pageSize, $pageNumber);
返回的数据:
{
"total": 30,
"per_page": 5,
"current_page": 2,
"last_page": 6,
"next_page_url": "/?page=3",
"prev_page_url": "/?page=1",
"from": 6,
"to": 10,
"data": {
"5": {
"userId": "564110eadcb39832268ea873",
"email": "dsdfgdfg@il.com",
"isActive": true,
"firstName": "dsdfgdfg",
"lastName": "dsdfgdfg",
"permissionType": "dsdfgdfg"
},
"6": {
"userId": "564110ea2169bc358a3b65c2",
"email": "dsdfgdfg@d.com",
"isActive": false,
"firstName": "dsdfgdfg",
"lastName": "dsdfgdfg",
"permissionType": "dsdfgdfg"
},
"7": {
"userId": "564110eaee662f30c4bd6772",
"email": "dsdfgdfg@dsdfgdfg.com",
"isActive": true,
"firstName": "dsdfgdfg",
"lastName": "dsdfgdfg",
"permissionType": "dsdfgdfg"
},
"8": {
"userId": "dsdfgdfg",
"email": "dsdfgdfg@dsdfgdfg.com",
"isActive": true,
"firstName": "dsdfgdfg",
"lastName": "dsdfgdfg"
},
"9": {
"userId": "564110eaf9526eb5ddd673a4",
"email": "dsdfgdfg@dsdfgdfg.com",
"isActive": true,
"firstName": "dsdfgdfg",
"lastName": "dsdfgdfg"
}
}
}
TIA
答案 0 :(得分:8)
问题是ids
时array_slice
仍然是数组的键。但由于缺少某些键,尤其是0, 1, 2, …
,因此在编码为json时,数组将被视为关联(['key1'=>'value1', 'key2'=>'value2', …]
)而不是数字索引(['value1', 'value2', …]
)。
解决方案是通过array_slice(…)
电话接听array_values()
。
return new LengthAwarePaginator(array_values($itemsForCurrentPage), count($this->orgUsers), $pageSize, $pageNumber);
修改:如果您的$arrayOfData
是Eloquent / Illuminate Collection
,您可以在其上使用->slice($offset, $pageSize)->values()
方法。看起来更好!