You mean simething like this?
$list = [
[
'student' => 'Jaime Thomas',
'subjects' => [
[
'subject' => 'Physics',
'marks' => 0
]
]
]
];
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am working on a exam portal project in laravel. I want to create an array of objects. One object must have student name property and in that same object I want to push another subject array for that student. I want output like this...
[
{
"student": "Jaime Thomas",
"subjects": [
{
"subject": "Physics",
"marks_": 0
},
{
"subject": "Chemistry",
"marks_": 0
}
]
},
{
"student": "Jaime Dey",
"subjects": [
{
"subject": "Physics",
"marks_": 0
},
{
"subject": "Chemistry",
"marks_": 0
}
]
}
]
Here is my code...
$exam_data = tbl_exam_data::join('tbl_subjects', 'tbl_subjects.subject_id', 'exam_data_subject_id')
->where('exam_data_exam_id', $exam_id)->get([
'exam_data_id', 'subject_name', 'subject_id', 'has_negative_marking', 'negative_marks'
]);
$exam_details = tbl_exam::find($exam_id);
$usersData = User::where('user_id', 2)->where("stud_class", $exam_details->exam_class_id)->where("stud_sub_branch", $exam_details->exam_branch_id)->get(['name', 'id']);
$studentsArray = [];
foreach ($usersData as $user) {
$studentsArray = array(
"student" => $user->name,
"subjects" => []
);
foreach ($exam_data as $subject) {
$att_exams = tbl_student_attended_exam::where('attended_exams_subject_id', $subject->subject_id)
->where('attended_exams_student_id', $user->id)
->first();
if ($att_exams) {
$marks = tbl_student_attended_questions::where('student_attended_question_std_exams_attended_id', $att_exams->attended_exams_id)->get();
$right = 0;
$wrong = 0;
$total_marks = $marks->sum('student_attended_question_marks');
foreach ($marks as $mark) {
if ($mark->student_attended_question_is_correct_answer == 0) {
$wrong++;
} else {
$right++;
}
}
$total_negative_marks = $wrong * $subject->negative_marks;
$subjectsArray[] = array(
"subject" => $subject->subject_name,
"marks_" => $total_marks - $total_negative_marks,
);
} else {
$subjectsArray[] = array(
"subject" => $subject->subject_name,
"marks_" => 0,
);
}
}
$studentsArray[]["subjects"] = array($subjectsArray);
}
return $studentsArray;
Please or to participate in this conversation.