Home  >  Article  >  Backend Development  >  How to Fetch Key-Value Pairs into Associative Arrays Using PDO?

How to Fetch Key-Value Pairs into Associative Arrays Using PDO?

Susan Sarandon
Susan SarandonOriginal
2024-10-22 16:37:03884browse

How to Fetch Key-Value Pairs into Associative Arrays Using PDO?

PDO fetchAll Group Key-Value Pairs into Associative Array

When working with queries that return key-value pair data, it's often desirable to group these pairs into an associative array for easier manipulation. While conventional approaches like using fetchAll(PDO::FETCH_ASSOC) and subsequent manual array population can be effective, there are other alternatives.

fetchAll(PDO::FETCH_KEY_PAIR)

One efficient solution for this task is fetchAll(PDO::FETCH_KEY_PAIR). This method directly returns an associative array where the key and value columns from the query are automatically mapped as array keys and values, respectively. For instance, a query like SELECT 'first_name', 'Tom' would result in an array like ['first_name' => 'Tom'].

Code Sample:

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

This method provides a convenient and efficient way to retrieve key-value pairs in associative array format, eliminating the need for additional array manipulation.

The above is the detailed content of How to Fetch Key-Value Pairs into Associative Arrays 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