Home  >  Article  >  Backend Development  >  How to Efficiently Convert a Database Result Into an Associative Array Using PDO?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-22 20:04:02265browse

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>

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>

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>

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!

Statement:
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