"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 Convert Database Query Results to Key-Value Arrays Using PDO?

How to Efficiently Convert Database Query Results to Key-Value Arrays Using PDO?

Published on 2024-11-07
Browse:206

How to Efficiently Convert Database Query Results to Key-Value Arrays Using PDO?

Achieving Efficient Key-Value Array Conversion from Database Queries Using PDO

In database manipulation scenarios, extracting data from a table into an associative array often arises. For queries featuring a key-value structure, the traditional approach involves two steps: fetching the results into a flat array and subsequently iterating through it to construct the desired associative array.

Nevertheless, an alternative solution exists that directly returns the associative array from the database query. Using the PDO fetchAll method with the PDO::FETCH_KEY_PAIR constant, one can achieve this efficiently:

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

This solution eliminates the need for additional processing and significantly simplifies the code. Notably, its compatibility with PostgreSQL 9.1 and PHP 5.3.8 makes it a viable option for a wide range of applications.

Release Statement This article is reprinted at: 1729583835 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