答案 0 :(得分:0)
您只需将此代码段放入函数buildExamData
:
protected function buildExamData($examdata) {
$examIdsNesting = [];
foreach ($examdata as $examdatum) {
$examIdsNesting[] = array(
'Exam Name' => $examdatum->Name,
'Exam Code' => $examdatum->ExamCode,
'Exam Details' => $examdatum->Details,
'Exam Owner' => $examdatum->Owner,
);
}
return $examIdsNesting;
}
然后,每次要执行此操作时,只需致电buildExamData()
,例如:
public function GetListOfExams(Request $request)
{
//select Name, ExamCode,Details, Owner, from exams where owner = Owner and status = 1;
$owner = $request->get('owner'); //get this from GET request
$status = 1; //it is intialized here
$examdata = Exam::select('Name', 'ExamCode', 'Details', 'Owner')->where(
array(
'Owner' => $owner,
'status'=> $status
)
)->get();
return $examdata->isEmpty()
? response()->json('Exam not found for this Owner', 404)
: response()->json($this->buildExamData($examdata), 200);
}
请注意,我对
buildExamData()
功能进行了一些重构,因此您不需要array_push()
Ps:如果您不想公开您的源代码,我可以删除代码部分,只留下解释