Home >Database >Mysql Tutorial >How Can I Efficiently Fetch Key-Value Pairs from a Database into an Associative Array Using PDO?

How Can I Efficiently Fetch Key-Value Pairs from a Database into an Associative Array Using PDO?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 03:39:10595browse

How Can I Efficiently Fetch Key-Value Pairs from a Database into an Associative Array Using PDO?

Fetch Key-Value Pairs into Associative Array Efficiently Using PDO

When working with database queries, it is often necessary to convert the result set into an associative array, where the keys correspond to a particular column and the values to another. This can be achieved using PDO's fetchAll method.

One common approach involves using PDO::FETCH_ASSOC to obtain a flat array. However, this method requires a subsequent foreach loop to create the desired associative array.

An Alternative Solution Using PDO::FETCH_KEY_PAIR

For scenarios where the query returns key-value pairs, PDO offers a more efficient solution: PDO::FETCH_KEY_PAIR. This flag instructs PDO to return a unique associative array, where the keys and values correspond to the specified columns in the query.

To use this approach, the following code can be employed:

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

In this example, the keys of the $r array will correspond to the name column, while the values will correspond to the value column. This technique allows for direct access to the data in the desired format without any additional processing.

The above is the detailed content of How Can I Efficiently Fetch Key-Value Pairs from a Database 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