How to Efficiently Convert a Database Result Into an Associative Array Using PDO?

Susan Sarandon
Release: 2024-10-22 20:04:02
Original
268 people have browsed it

How to Efficiently Convert a Database Result Into an Associative Array Using PDO?

Converting Result Set into an Associative Array Using Key-Value Pairs with PDO

When working with a query that returns key-value pairs, such as:

<code class="sql">SELECT `key`, `value` FROM `settings`;</code>
Copy after login

You may desire an associative array where the keys and values correspond to the returned data. Typically, this is achieved through a process involving:

<code class="php">$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'];
}</code>
Copy after login

While this method is common, it requires multiple iterations and potential performance issues. However, there is an alternative solution available:

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

The PDO::FETCH_KEY_PAIR constant allows you to retrieve data as an associative array directly from the query, simplifying the process and potentially improving performance on larger result sets.

The above is the detailed content of How to Efficiently Convert a Database Result Into an Associative Array Using PDO?. 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!