PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, January 2, 2022

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

 January 02, 2022     laravel, php     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing