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');
.
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.
Is there another way to do this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…