2017-09-14 65 views
1

我執行此查詢有沒有一種方法可以獲取按PDO值排列的兩個colums組合的關聯數組?

$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

我可能會錯,但我不認爲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']; 
} 
相關問題