有没有办法获取按PDO两个列的值分组的关联数组?

时间:2017-09-14 17:48:26

标签: php mysql pdo

我执行了这个查询

 $sql = "
 SELECT cls
     , sctn
     , COUNT(case when gender='M' then 1 end) boys
     , COUNT(case when gender='F' then 1 end) girls
   FROM student_table
  WHERE active = 1 
  group 
     by cls
     , sctn";


 $stmt->query($sql)->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);

然后我得到了这个结果

 Array
    (
      [1st] => Array(
            [0] => Array (
                    [sctn] => A
                    [boys] => 8
                    [girls] => 7
                )
            [1] => Array (
                    [sctn] => B
                    [boys] => 5
                    [girls] => 4
                )
        )
     [2nd] => Array (
            [0] => Array (
                    [sctn] => A
                    [boys] => 3
                    [girls] => 7
                )
            [1] => Array  (
                    [sctn] => B
                    [boys] => 8
                    [girls] => 5
                )
        )
     [3rd] => Array (
            [0] => Array (
                    [sctn] => A
                    [boys] => 9
                    [girls] => 11
                )
            [1] => Array  (
                    [sctn] => B
                    [boys] => 5
                    [girls] => 17
                )
        )
    )

但我期待的结果是

Array
(
  [1st] => Array(
        [A] => Array (
                [boys] => 8
                [girls] => 7
            )
        [B] => Array (
               [boys] => 5
                [girls] => 4
            )
    )
 [2nd] => Array (
        [A] => Array (
                [boys] => 3
                [girls] => 7
            )
        [B] => Array  (
                [boys] => 8
                [girls] => 5
            )
    )
 [3rd] => Array (
        [A] => Array (
               [boys] => 9
                [girls] => 11
            )
        [B] => Array  (
                [boys] => 5
                [girls] => 17
            )
    )
)

在这里,我想要分级明智,明智和性别明智

我还需要sctn值作为嵌套数组的键

有没有办法根据我的SELECT查询获得此结果?

1 个答案:

答案 0 :(得分:1)

我可能会弄错,但我不认为PDO::FETCH_GROUP可以与这样的多个群组合作。

我认为您只需要一次一行地将其添加到您想要的结构中,而不是使用fetchAll

$result = $pdo->query($sql);

while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
    $array[$row['cls']][$row['sctn']]['boys'] = $row['boys'];
    $array[$row['cls']][$row['sctn']]['girls'] = $row['girls'];
}