"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Efficiently Retrieve Key-Value Pairs into an Associative Array with PDO FetchAll?

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

Published on 2024-10-31
Browse:934

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

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

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.

Release Statement This article is reprinted at: 1729583957 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3