Home >Backend Development >PHP Tutorial >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!