Home > Software engineering >  How to get all the arrays of the same value into a new array
How to get all the arrays of the same value into a new array

Time:12-28

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,
                ]]);


        }

CodePudding user response:

You can do something like this

$data = [...] //your array
  
$grouped = array_values(
array_reduce($data, function(array $res, $item){
 $subject = $data['subjectid'];
  $existing = $res[$subject] ?? [];
  $res[$subject] = array_merge($existing, [$item]);
  return $res;
}, []));

CodePudding user response:

You can simply try this to group by subjectid

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