PDO将所有组键值对组合到assoc数组中 [英] PDO fetchAll group key-value pairs into assoc array
问题描述
每隔一段时间,我都会遇到一种类似以下查询的情况:
Every now and then, I get into a situation when I have a query similar in kind to:
SELECT `key`, `value` FROM `settings`;
在这种情况下,我想使用key
& value
作为该数组的相应条目,例如如果数据库包含:('first_name', 'Tom'), ('last_name', 'Jeferson')
,则数组应为array('first_name' => 'Tom', 'last_name' => 'Jeferson');
.
In this case, I want to get an associative array, using values of key
& value
as 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');
.
最常用的方法是:
$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'];
}
*另一种方法是通过两次调用fetchAll(PDO::FETCH_COLUMN)
&然后使用array_combine
创建数组.但是,由于涉及两个数据库两个调用,因此我将其保留为一个选项.
*The other way to do this is by calling fetchAll(PDO::FETCH_COLUMN)
two times & then using array_combine
to create the array. However, since it involves two calls two the database, I leave out this as an option.
还有另一种方法吗?
推荐答案
对于您的问题,有非常好的解决方案,即:
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);
在PostgreSQL 9.1和在Windows 7 x64上运行的PHP 5.3.8上为我工作.
Works for me, on PostgreSQL 9.1, and PHP 5.3.8 running on Windows 7 x64.
这篇关于PDO将所有组键值对组合到assoc数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!