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

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

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

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


        
8条回答
  •  暖寄归人
    2020-11-28 08:14

    The accepted answer is essentially a cargo cult code, that does its job only by accident, but makes no sense by itself.

    PDO::FETCH_GROUP and PDO::FETCH_UNIQUE are mutual exclusive fetch modes, that cannot be used together. Only one of them would work. When you combine them, the latter takes over and \PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE is actually just PDO::FETCH_UNIQUE.

    Beside that, the question is ambiguous by itself, the OP wants his array to be indexed by the unique field, whereas he called it grouping which raised a controversy in the answers as well.

    So to make it straight:

    • to index an array with unique values (when you want the resulting array to be indexed by the employee's name, given they are unique), the fetch mode must be PDO::FETCH_UNIQUE:

      $pdo->query('SELECT name, e.* FROM employee e')->fetchAll(PDO::FETCH_UNIQUE);
      
    • to group the results (when you want to group employees by department, for example), the fetch mode must be PDO::FETCH_GROUP:

      $pdo->query('SELECT dept_id, e.* FROM employee e')->fetchAll(PDO::FETCH_GROUP);
      

    in both cases the field to be used as the first level array index, must be listed first in the SELECT field list.

    A note on the PDO::FETCH_ASSOC. Given that fetch mode for the preferred result format could be set once for all in the constructor, it makes no sense to list it explicitly as well.

提交回复
热议问题