How to Retrieve Associative Arrays Grouped by Column Values with PDO?

Linda Hamilton
Release: 2024-10-22 07:38:31
Original
146 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!