In certain scenarios, retrieving data from a database often requires extracting key-value pairs. The typical approach involves storing the data in a flat array, followed by iterating through it to construct the desired associative array. However, this process can be tedious.
To simplify this task, PDO (PHP Data Objects) offers a more efficient solution:
Instead of relying on multiple database calls or extensive array manipulation, you can use PDO::FETCH_KEY_PAIR. This fetch mode allows PDO to automatically group key-value pairs into an associative array, eliminating the need for manual processing.
To illustrate, consider the following example:
$q = $db->query("SELECT `name`, `value` FROM `settings`;"); $r = $q->fetchAll(PDO::FETCH_KEY_PAIR);
In this scenario, the query results will be directly stored as an associative array where the name column values serve as keys and the value column values serve as corresponding array values. The resulting array will be structured as follows:
$r = [ 'first_name' => 'Tom', 'last_name' => 'Jeferson', ];
Note that PDO::FETCH_KEY_PAIR is only supported in certain database drivers. For instance, it is available in the PostgreSQL and MySQL drivers. To check the availability of this fetch mode for your database, consult the PDO documentation.
The above is the detailed content of How Can PDO::FETCH_KEY_PAIR Simplify Retrieving Key-Value Pairs from a Database?. For more information, please follow other related articles on the PHP Chinese website!