php PDO fetchAll 将键值对分组到关联数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7451126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:41:34  来源:igfitidea点击:

PDO fetchAll group key-value pairs into assoc array

phpmysqlpdo

提问by Gajus

Every now and then, I get into a situation when I have a query similar in kind to:

时不时地,当我有类似的查询时,我会遇到以下情况:

SELECT `key`, `value` FROM `settings`;

In this case, I want to get an associative array, using values of key& valueas respective entries of that array, e.g. if the database contained: ('first_name', 'Tom'), ('last_name', 'Jeferson'), the array should be array('first_name' => 'Tom', 'last_name' => 'Jeferson');.

在这种情况下,我想获得一个关联数组,使用key& 的值value作为该数组的相应条目,例如,如果数据库包含: ('first_name', 'Tom'), ('last_name', 'Jeferson'),则数组应该是array('first_name' => 'Tom', 'last_name' => 'Jeferson');.

The most common way to do this is:

最常见的方法是:

$settings_flat = $db
    ->query("SELECT `name`, `value` FROM `settings`;")
    ->fetchAll(PDO::FETCH_ASSOC);

$settings   = array();

foreach ($settings_flat as $setting) {
    $settings[$setting['name']] = $setting['value'];
}

*The other way to do this is by calling fetchAll(PDO::FETCH_COLUMN)two times & then using array_combineto create the array. However, since it involves two calls two the database, I leave out this as an option.

*另一种方法是调用fetchAll(PDO::FETCH_COLUMN)两次,然后使用array_combine来创建数组。但是,由于它涉及两个数据库的两个调用,因此我将其作为一个选项省略。

Is there another way to do this?

有没有另一种方法可以做到这一点?

回答by devdRew

For your problem there is pretty ready solution, that is:

对于您的问题,有非常现成的解决方案,即:

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

Works for me, on PostgreSQL 9.1, and PHP 5.3.8 running on Windows 7 x64.

适用于我,在 PostgreSQL 9.1 和 PHP 5.3.8 上运行 Windows 7 x64。

回答by Jignesh Rawal

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