laravel - 无法在 foreach 之外获取数据
Posted
技术标签:
【中文标题】laravel - 无法在 foreach 之外获取数据【英文标题】:laravel - unable to get data outside foreach 【发布时间】:2021-11-05 01:17:30 【问题描述】:dump($data)
在foreach
循环之外只给我 1 个数据,而foreach
内部的dump($data)
显示所有数据行数组。我如何也可以获取 foreach 之外的所有数据行?
$skillId = $request->skillId;
if (CourseFiles::where('skillId', $skillId)->exists())
$courseId = CourseFiles::where('skillId', $skillId)->get(['courseId']);
foreach ($courseId as $row)
$id = Course::find($row);
$data = [];
$data['courseDisplayName'] = $id[0]['courseDisplayName'];
$data['courseInfo'] = $id[0]['courseUniqueName'];
$data['paidStatus'] = $id[0]['paid_status'];
$data['coursePatternsId'] = $id[0]['course_patterns_id'];
$fileId = CourseFiles::where('skillId', $skillId)->get(['fileId']);
$id = Uploads::find($fileId);
$data['filePath'] = $id[0]['FilePath'];
$contentTypeID = $id[0]['FileType'];
$id = ContentTypes::find($contentTypeID);
$data['file_height'] = $id[0]['height'];
$data['file_width'] = $id[0]['width'];
dump($data);
//dump($data);
if ($data)
return response()->json([
'message' => 'Fetched Data successfully',
'data' => $data,
'statusCode' => 200,
'status' => 'success'
], 200);
编辑:
$response[]=$data;
$response->paginate(5);
Error: Call to a member function paginate() on array
【问题讨论】:
需要在 foreach 中的下一次迭代之前推送每个数组 @RushikeshGanesh 那么,我应该在那里提供哪一行代码?你能给我一个示例代码行吗? 只需将 $data =[] 放在 foreach 之前就可以了 @RushikeshGanesh$response[]=$data;
- 我已经给出了这样的结果,现在它正在工作。但我需要对结果进行分页。$response->paginate(5)
显示错误Error: Call to a member function paginate() on array
。我该怎么做分页在这里?
【参考方案1】:
就这样吧,
$output = array();
foreach ($courseId as $key => $row)
$id = Course::find($row);
$fileId = CourseFiles::where('skillId', $skillId)->get(['fileId']);
$idtwo = Uploads::find($fileId);
$idthree = ContentTypes::find($idtwo[0]['FileType']);
//your data want to push to array
$output[$key] = array(
'courseDisplayName' => $id[0]['courseDisplayName'];
'courseInfo' => $id[0]['courseUniqueName'];
'paidStatus' => $id[0]['paid_status'];
'coursePatternsId' => $id[0]['course_patterns_id'];
'filePath' => $idtwo[0]['FilePath'];
'file_height' => $idthree[0]['height'];
'file_width' => $idthree[0]['width'];
);
dd($output);
【讨论】:
谢谢。我真的在寻找优化的解决方案。非常感谢【参考方案2】:在控制器中为其添加新功能
$data = $this->paginate($myArray);
在那之后为分页创建那个函数
public function paginate($items, $perPage = 5, $page = null, $options = [])
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
返回 $data 作为响应
【讨论】:
对于Collection
,需要导入哪个类?
使用 Illuminate\Support\Collection;以上是关于laravel - 无法在 foreach 之外获取数据的主要内容,如果未能解决你的问题,请参考以下文章
在 foreach 循环中删除重复项(但计算它们) - Laravel 8