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
& 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');
.
在本例中,我希望获得一个关联数组,使用键值和值作为该数组的各自条目,例如,如果数据库包含:('first_name', 'Tom'), ('last_name', 'Jeferson'),数组应该是数组('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_combine
to 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?
还有别的办法吗?
2 个解决方案
#1
80
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上。
#2
-3
$query = $db->query("SELECT `name` AS name, `value` AS value FROM `settings`;");
$result = $query->fetchAll(PDO::FETCH_ASSOC);
#1
80
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上。
#2
-3
$query = $db->query("SELECT `name` AS name, `value` AS value FROM `settings`;");
$result = $query->fetchAll(PDO::FETCH_ASSOC);