Sunday, January 2, 2022

[FIXED] How to get all the arrays of the same value into a new array

Issue

I have the array below

[0: {id: 2, restult_typeid: 1, studentid: 3, academic_periodid: 1, subjectid: 2, classroomid: 6,…}
1: {id: 2, restult_typeid: 2, studentid: 3, academic_periodid: 1, subjectid: 2, classroomid: 6,…}
2: {id: 2, restult_typeid: 3, studentid: 3, academic_periodid: 1, subjectid: 2, classroomid: 6,…}
3: {id: 2, restult_typeid: 4, studentid: 3, academic_periodid: 1, subjectid: 2, classroomid: 6,…}
4: {id: 2, restult_typeid: 1, studentid: 3, academic_periodid: 1, subjectid: 1, classroomid: 6,…}]

i want to turn this array into this, that is all the array with the same subjectid should been in a group and vice versa

[
0: [{id: 2, restult_typeid: 1, studentid: 3, academic_periodid: 1, subjectid: 2, classroomid: 6,…}, {id: 2, restult_typeid: 2, studentid: 3, academic_periodid: 1, subjectid: 2, classroomid: 6,…}, {id: 2, restult_typeid: 3, studentid: 3, academic_periodid: 1, subjectid: 2, classroomid: 6,…}, {id: 2, restult_typeid: 4, studentid: 3, academic_periodid: 1, subjectid: 2, classroomid: 6,…}]
1: [{id: 2, restult_typeid: 1, studentid: 3, academic_periodid: 1, subjectid: 1, classroomid: 6,…}]
]

i have tried this

$allSubjects = [];
        $subs = [];
        foreach($result as $res){
            // solve for everysubjectid
            $subject = array_push($allSubjects, $res->subjectid);
            $returnValue = array_unique($allSubjects);

                $getScores = array_push($subs, [$res->subjectid=>[
                        'type'=>$res->restult_typeid,
                        'subjecttitle'=>$res->subjecttitle,
                        'score'=>$res->score_obtained,
                ]]);


        }

Solution

You can simply try this to group by subjectid

$subs = [];
foreach($result as $res){
    $subs[$res->subjectid][] = $res;
}


Answered By - Manash Kumar

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.