本文介绍了PHP PDOStatement:获取一行,作为第一列作为数组的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PDOStatement来查询数据库.每当我得到返回的行时,我都希望将其提取到数组中,并以$row[0]作为键,并将该行中的后续元素作为值.

I am using PDOStatement to query the database. Whenever I get a returned row, I want it to be fetched into an array, with the $row[0] as the key, and the subsequent elements in the row as the values.

我当然可以编写foreach循环和if条件语句的组合来完成这项工作,如下所示:

I can, of course, write a combination of foreach loops and if conditionals to do the job, such as the below:

private static function GetMySQLResult($dbname, $sqlString) {


        $dbh =  self::ConstructPDOObject($dbname);
         $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $result=array();
         foreach ($dbh->query($sqlString) as $row)
         {
            $result[$row[0]][]=$row[1];  // the simplest case for 2 columns, should add more to handle more columns

         }

         return $result;

}

但是我正在寻找一种现有的方法;有没有这样的方法已经存在?

but I am looking for an existing method; is there such a method already exist?

推荐答案

贷方转到devdRew. 在此处检查其他问题.

Credits go to devdRew. Check the other question here.

显然,您可以按照答案中的说明进行操作.我也检查了一下,效果很好.

Apparently, you can as stated in the answer. I checked as well and it works great.

$q = $db->query("SELECT `name` AS name, `value` AS value FROM `settings`;");
$r  = $q->fetchAll(PDO::FETCH_KEY_PAIR);

编辑

此答案要求您最多指定2列:1个键和1个值.如果您需要从数据库中检索更多密钥,请查看下面的答案并阅读@nullabilty的注释.对于那些懒惰的人,这是他的方法:

This answer requires that you specify maximum 2 columns: 1 key and 1 value. If you need to retrieve more keys from the database, check the answer below and read @nullabilty's comment. For those who are lazy, here is his method:

$q->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC);

这篇关于PHP PDOStatement:获取一行,作为第一列作为数组的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 07:39