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

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

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

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


        
8条回答
  •  时光说笑
    2020-11-28 08:01

    This answer is out of date, please see this other answer instead.


    It looks like there's no way to do this as part of fetchAll.

    Your best bet is going to be creating a class that extends PDO, adding a utility method to it.

    public function queryKeyedAssoc($query, $params, $key) {
        $sth = $this->prepare($query);
        $sth->execute($params);
        $res = array();
        while($row = $sth->fetch(PDO::FETCH_ASSOC))
            $res[ $row[$key] ] = $row;
        return $res;
    }
    

提交回复
热议问题