如何使用PHP数组对MySQL中的结果进行分组?

时间:2016-07-05 19:56:23

标签: php mysql

我的数据库中有2个表。

表A

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

表B

StudentID            Courses
  1                    Math
  1                    Science
  2                    Art

现在我使用INNER JOIN查询

$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;
}

我得到的结果只是按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'

我希望展示的是对它们进行分组,以便我不会重复学生。我怎样才能做到这一点?提前致谢

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'
        )

1 个答案:

答案 0 :(得分:1)

首先检查数组键是否存在:

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

但请注意,您只会获得其中一个类,例如Math,然后Science将被跳过,因为您已经在阵列中为该学生开设了一门课程。

如果您想保留课程信息,同时不重复学生的详细信息,那么您必须更深入了解:

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 ...;
}