Home > Backend Development > PHP Tutorial > How to Retrieve Associative Arrays Grouped by Specific Column with PDO?

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

Linda Hamilton
Release: 2024-10-22 07:40:02
Original
1058 people have browsed it

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

Fetching Associative Arrays Grouped by Column Values with PDO

Question:

In a database with multiple columns (e.g., "name," "age," "sex," and "position"), how can we retrieve associative arrays in a specific format using PDO's fetchAll method, where each array's key is a field from a specified column (e.g., "name") and the values are the corresponding rows for that key?

Answer:

Using PDO's fetchAll method, we can specify the following flags to achieve the desired result:

<code class="php">->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE);</code>
Copy after login

By combining FETCH_GROUP and FETCH_UNIQUE, PDO will automatically group results by the specified column and set the first column as the key for each group, while excluding duplicate records. This eliminates the additional nesting level or the need for post-processing operations like current.

Example:

Consider the following sample dataset:

name age sex position
Antony 34 M programmer
Sally 30 F manager
Matthew 28 M designer

Using the recommended fetch method, we can retrieve the desired result array:

<code class="php">$result = $pdo->query('SELECT * FROM employee')->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE);

print_r($result);</code>
Copy after login

This will output the following associative array:

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

The above is the detailed content of How to Retrieve Associative Arrays Grouped by Specific Column 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