Home > Database > Mysql Tutorial > How Can I Efficiently Fetch Key-Value Pairs from a PDO Query as an Associative Array?

How Can I Efficiently Fetch Key-Value Pairs from a PDO Query as an Associative Array?

DDD
Release: 2024-11-24 18:06:19
Original
649 people have browsed it

How Can I Efficiently Fetch Key-Value Pairs from a PDO Query as an Associative Array?

PDO FetchAll Group Key-Value Pairs into Associative Array

When working with queries that return key-value pairs, it's often desirable to retrieve the results as an associative array. Consider the following query:

SELECT `key`, `value` FROM `settings`;
Copy after login

The goal is to obtain an associative array where the keys correspond to the key column and the values correspond to the value column.

The traditional approach involves fetching the results using PDO::FETCH_ASSOC and then manually creating the associative array using a loop:

$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'];
}
Copy after login

However, there is a more efficient way to achieve the same result using PDO::FETCH_KEY_PAIR:

$q = $db->query("SELECT `name`, `value` FROM `settings`;");
$r = $q->fetchAll(PDO::FETCH_KEY_PAIR);
Copy after login

This method directly returns an associative array where the keys correspond to the key column and the values correspond to the value column.

This approach is not only more concise, but it also avoids unnecessary looping and array creation. It is a convenient and efficient solution for converting key-value pair results into an associative array.

The above is the detailed content of How Can I Efficiently Fetch Key-Value Pairs from a PDO Query as an Associative Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template