Is there a way to fetch associative array grouped by the values of a specified column with PDO?

前端 未结 8 1392
轮回少年
轮回少年 2020-11-28 07:39

For example, let\'s use some simple data set

+---------+------+------+------------+
| name    | age  | sex  | position   |
+---------+------+------+---------         


        
相关标签:
8条回答
  • 2020-11-28 08:19

    It doesn't look like anyone has mentioned this variation, so, for the benefit of future Googlers:

    Combine the \PDO::FETCH_GROUP and \PDO::FETCH_COLUMN flags. This vastly simplified my SQL statement and returned the exact result set I wanted. It's fast, too.

    $this->database->query('SELECT t.fk, t.id FROM my_table t ORDER BY t.fk ASC, t.id ASC')
      ->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_COLUMN);
    

    Where t.fk has a one-to-many relationship with t.id.

    I didn't have to concern myself with a GROUP BY statement or MySQL's finicky handling of grouping on multiple fields. Best of all, I received results in the form of:

    [
      foreign_key_1 => [
        0 => 11111,
        1 => 22222,
        2 => 33333,
      ],
      foreign_key_2 => [
        0 => 44444,
        1 => 55555,
        2 => 66666,
      ],
      foreign_key_3 => [
        0 => 77777,
        1 => 88888,
        2 => 99999,
      ],
    ];
    

    Rather than:

    [      
      foreign_key_1 => [
        0 => [
          id => 11111,
        ],
        1 => [
          id => 22222,
        ],
        2 => [
          id => 33333,
        ],
      ],
      foreign_key_2 => [
        0 => [
          id => 44444,
        ],
        1 => [
          id => 55555,
        ],
        2 => [
          id => 66666,
        ],
      ],
      foreign_key_3 => [
        0 => [
          id => 77777,
        ],
        1 => [
          id => 88888,
        ],
        2 => [
          id => 99999,
        ],
      ],
    
    ];
    

    Hope it helps someone out there!


    For reference: https://phpdelusions.net/pdo/fetch_modes

    0 讨论(0)
  • 2020-11-28 08:25

    Key assoc array

    PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC
    
    0 讨论(0)
提交回复
热议问题