Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

php - 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`;

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...