Home >Database >Mysql Tutorial >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`;
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']; }
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);
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!