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";
    }
}