问题描述
时不时地,当我有类似的查询时,我会遇到以下情况:
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.
还有其他方法可以做到这一点吗?
Is there another way to do this?
推荐答案
对于你的问题,有现成的解决方案,那就是:
For your problem there is pretty ready solution, that is:
$q = $db->query("SELECT `name`, `value` FROM `settings`;");
$r = $q->fetchAll(PDO::FETCH_KEY_PAIR);
适用于我,在 PostgreSQL 9.1 和 PHP 5.3.8 上运行 Windows 7 x64.
Works for me, on PostgreSQL 9.1, and PHP 5.3.8 running on Windows 7 x64.
这篇关于PDO fetchAll 将键值对分组到关联数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!