How can the PDO::FETCH_GROUP method be utilized in PHP to group query results by a specific identifier, such as a person's ID?
To utilize the PDO::FETCH_GROUP method in PHP to group query results by a specific identifier, such as a person's ID, you can fetch the results from the database using a query and then use FETCH_GROUP with the specific identifier column. This method will return an associative array where the keys are the unique identifiers and the values are arrays of rows with that identifier.
// Assume $pdo is your PDO connection
$query = "SELECT id, name, age FROM people";
$stmt = $pdo->query($query);
$results = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
foreach ($results as $personId => $personData) {
echo "Person ID: " . $personId . "\n";
foreach ($personData as $person) {
echo "Name: " . $person['name'] . ", Age: " . $person['age'] . "\n";
}
}
Keywords
Related Questions
- What is the best PHP function to use for sorting an array of objects by a specific value within each object?
- What are the best practices for handling user authentication in PHP, especially in admin login scenarios?
- In what situations should one consider extending the time calculation logic to include date factors in PHP?