How to Efficiently Retrieve Key-Value Pairs into an Associative Array with PDO FetchAll?

Barbara Streisand
Release: 2024-10-22 20:54:02
Original
126 people have browsed it

How to Efficiently Retrieve Key-Value Pairs into an Associative Array with PDO FetchAll?

PDO FetchAll: Group Key-Value Pairs into an Associative Array

In database queries that return key-value pairs, it is often convenient to retrieve the data as an associative array, with the values mapped to their respective keys. While there are common methods to achieve this, such as using fetchAll(PDO::FETCH_ASSOC) followed by manual iteration to create the array, this approach can be cumbersome.

An alternative solution, specifically designed for this purpose, is to use the fetchAll(PDO::FETCH_KEY_PAIR) option. This method automatically creates an associative array with the query results, mapping the first column to the keys and the second column to the values.

To demonstrate this, consider a query that retrieves name and value columns from the settings table:

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

In this case, if the database contained rows like ('first_name', 'Tom') and ('last_name', 'Jeferson'), the resulting $r array would be:

Array(
    'first_name' => 'Tom',
    'last_name'  => 'Jeferson'
)
Copy after login

This method provides a straightforward and efficient way to retrieve key-value pairs into an associative array, eliminating the need for manual array creation. It is supported by modern PHP versions and some popular databases like PostgreSQL.

The above is the detailed content of How to Efficiently Retrieve Key-Value Pairs into an Associative Array with PDO FetchAll?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!