我在控制器中的功能在下面
public function getStudentsinGrade($grade, $school_id){
$students = Student::where('school_id', $school_id)->get();
$this -> grade = $grade;
$gradeStudent= $students->filter(function($value,$key){
return $value->grade == $this->grade;
});
if(count($gradeStudent) > 0){
return response()->json($gradeStudent);
}
else{
return response('No Registered Student');
}
}下面是我得到的回应
*{
"2": <---this number here is the problem and it appeared when get API response
{
"id": 14,
"student_name": "Polly Grain",
"gender": "Female",
"stream_id": 1,
"school_id": 1,
"final_year_id": 2,
"grade": "Form Four"
},
"3": {
"id": 15,
"student_name": "Polly Grain",
"gender": "Male",
"stream_id": 3,
"school_id": 1,
"final_year_id": 2,
"grade": "Form Four"}
}*我想要得到的回应是
{ "id":1,"student_name":"sae sddat",“性别”:“男性”,"stream_id":2,"school_id":10,"final_year_id":12,"Form 1“},{ "id":1,"student_name":"sae sddat",”性别“:”男性“,"stream_id":2,"school_id":10,"final_year_id":12,“年级”:"Form One“},{ "id":1,"student_name":"sae sddat",”性别“:”男性“,"stream_id":2,"school_id":10,"final_year_id":12,”student_name“:"Form One”}
发布于 2022-10-25 04:02:48
要解决这个问题,首先将集合转换为数组,然后使用array_values()函数消除那些困扰您的烦人的数组键。然后,将其转换回集合,并将其作为json响应传递。代码:
public function getStudentsinGrade($grade, $school_id){
$students = Student::where('school_id', $school_id)->get();
$this -> grade = $grade;
$gradeStudent= $students->filter(function($value,$key){
return $value->grade == $this->grade;
});
if(count($gradeStudent) > 0){
$gradeStudent = collect(array_values($gradeStudent->toArray()));
return response()->json($gradeStudent);
}
else{
return response('No Registered Student');
}
}现在,这将给出如下所需的结果:
{
"id": 14,
"student_name": "Polly Grain",
"gender": "Female",
"stream_id": 1,
"school_id": 1,
"final_year_id": 2,
"grade": "Form Four"
},
{
"id": 15,
"student_name": "Polly Grain",
"gender": "Male",
"stream_id": 3,
"school_id": 1,
"final_year_id": 2,
"grade": "Form Four"}
}发布于 2022-10-25 07:10:02
为什么不向查询中添加额外的where子句
public function getStudentsinGrade($grade, $school_id){
$students = Student::where('school_id', $school_id)
->where('grade', $grade)
->get();
if($students->count() > 0){
return response()->json($gradeStudent);
}
else{
return response('No Registered Student');
}
}https://stackoverflow.com/questions/74188824
复制相似问题