Home >Backend Development >PHP Tutorial >How to Retrieve Associative Arrays Grouped by Column Values with PDO?
Retrieving Associative Array Grouped by Column Values with PDO
Problem:
To efficiently organize a dataset into an associative array grouped by the values of a specified column, there is a need to find a way to bypass the unnecessary nesting level when using PDO's FETCH_GROUP|PDO::FETCH_ASSOC mode.
Solution:
By leveraging the combination of PDO::FETCH_GROUP and PDO::FETCH_UNIQUE modes, the desired array structure can be achieved with a single fetch operation.
The code snippet below demonstrates this approach:
<code class="php">$stmt = $pdo->query('SELECT * FROM employee'); $result = $stmt->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE);</code>
The PDO::FETCH_GROUP mode groups the rows by the values of the first column, while PDO::FETCH_UNIQUE ensures that only the first row for each unique group value is included in the result.
As a result, the $result array will contain the following structure:
<code class="php">Array ( [Antony] => Array ( [age] => 34 [sex] => M [position] => programmer ) [Sally] => Array ( [age] => 30 [sex] => F [position] => manager ) [Matthew] => Array ( [age] => 28 [sex] => M [position] => designer ) )</code>
This eliminates the unnecessary nesting level encountered when using PDO::FETCH_GROUP|PDO::FETCH_ASSOC alone, providing a more efficient and straightforward way to retrieve associative arrays grouped by column values.
The above is the detailed content of How to Retrieve Associative Arrays Grouped by Column Values with PDO?. For more information, please follow other related articles on the PHP Chinese website!