0

I have got 2 tables in my database.

Table A

StudentID      Name             Age
 1             John Doe         15
 1             John Doe         15
 2             Marry Smith      20

Table B

StudentID            Courses
  1                    Math
  1                    Science
  2                    Art

Right now I use INNER JOIN query

$query = $db->prepare("Select a.studentid, a.name, a.age, b.studentid, b.courses FROM tableA a INNER JOIN TABLEB b ON a.studentid = b.studentid");
$query->execute();
$stmt = $query->fetchAll(PDO::FETCH_ASSOC);

$everything = array();
$groupArray = array();

foreach($stmt as $row){
    $everything[] = $row;
}

foreach($everything as $e){
    $groupArray[$e['studentid']][] = $e;
}

The result I got was just grouped by studentID

1 => array (size=2)
     0 => array (size=5)
       'StudentID' => string '1'
       'Name' => string 'John Doe'
       'Age' => string '15'
       'StudentID' => string '1'
       'Courses' => string 'Math'
     1 => array (size=5)
       'StudentID' => string '1'
       'Name' => string 'John Doe'
       'Age' => string '15'
       'StudentID' => string '1'
       'Courses' => string 'Science'

2 => array (size=2)
     0 => array (size=5)
       'StudentID' => string '2'
       'Name' => string 'Marry Smith'
       'Age' => string '20'
       'StudentID' => string '2'
       'Courses' => string 'Art'

What I hope to display is sort of grouping them so I dont get duplicate students. How can I achieve this? Thanks in advance

1 => array (size=2)
     0 => array (size=5)
       'StudentID' => string '1'
       'Name' => string 'John Doe'
       'Age' => string '15'

       'Courses' => array(
          0 => String 'Math'
          1 => String 'Science'
        )
Winsanity
  • 61
  • 1
  • 5

1 Answers1

1

Check if the array key exists first:

foreach($everything as $e){
    if(!isset($groupArray[$e['studentid']])) {
        $groupArray[$e['studentid']][] = $e;
    }
}

But then note that you'll only get one of the classes, e.g. Math, and then Science will be skipped since you already have a course for that student in your array.

If you want to keep the class information, while not duplicating the student details, then you'll have to go a level deeper:

foreach($everything as $e){
    $id = $e['studentid'];
    if (!isset($groupArray[$id]) {
      ... first time seeing this student
        $groupArray[$id]['name'] = $e['name'];
        $groupArray[$id]['age'] = $e['age']
        $groupArray[$id]['classes'] = array();
    }        
    $groupArray[$id]['classes'] = .. details about class here ...;
}
Marc B
  • 356,200
  • 43
  • 426
  • 500