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

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

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

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


        
8条回答
  •  鱼传尺愫
    2020-11-28 08:06

    We can make Charles' solution a little nicer by extending the statement class instead:

    class MyPdo extends PDO {
        function __construct($host, $database_name, $username, $password, $options=array()) {
            $options = self::merge(array(
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_STATEMENT_CLASS => array('PdoPlusStatement', array()),
                PDO::ATTR_EMULATE_PREPARES => true,
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
            ), $options);
            $dsn = "mysql:host=$host;dbname=$database_name;charset=utf8";
            parent::__construct($dsn, $username, $password, $options);
        }
    }
    
    class PdoPlusStatement extends PDOStatement {
        protected function __construct() {}
    
        /**
         * @param array|mixed $input_parameters An array of values with as many elements as there are bound parameters in the SQL statement being executed, or one or more non-array arguments to be matched with sequential parameter markers.
         * @throws PDOException
         * @return PdoPlusStatement
         */
        public function execute($input_parameters=null) {
            $args = func_get_args();
            $argc = func_num_args();
            if($argc===0) {
                parent::execute();
            } else {
                if($argc===1 && is_array($args[0])) {
                    $args = $args[0];
                }
                parent::execute($args);
            }
            return $this;
        }
    
        /**
         * Returns an array containing all of the remaining rows in the result set
         * @return array An associative array using the first column as the key, and the remainder as associative values
         */
        public function fetchKeyAssoc() {
            return array_map('reset', $this->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC));
        }
    }
    

    Usage:

    $users = $pcs->query("SELECT name, user_id, discipline_id FROM wx_user")->fetchKeyAssoc();
    

提交回复
热议问题