How to use PDO::FETCH_GROUP to get a flat array?

117 Views Asked by At

I use PDOStatement::fetchAll with FETCH_GROUP and FETCH_ASSOC to get my table's primary key as the array key.

$objects = $stmt_obj->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_CLASS);

This leads to the following result:

Array
(
    [56] => Array
        (
            [0] => stdClass Object
                (
                    ...
                )
        )

    [39] => Array
        (
            [0] => stdClass Object
                (
                    ...
                )
        )

    [38] => Array
        (
            [0] => stdClass Object
                (
                    ...
                )
        )

    [71] => Array
        (
            [0] => stdClass Object
                (
                    ...
                )
        )
)

What can I do to get rid of the useless numbered array and get the following result:

Array
(
    [56] => stdClass Object
        (
            ...
        )

    [39] => stdClass Object
        (
            ...

    [38] => stdClass Object
        (
            ...
        )

    [71] => stdClass Object
        (
            ...
        )
)
2

There are 2 best solutions below

1
Barmar On

There's no need to map over the array. Add the PDO::FETCH_UNIQUE flag and the result will have each element as a single object, rather than an array of objects.

$objects = $stmt_obj->fetchAll(PDO::FETCH_GROUP | PDO::FETCH_CLASS | PDO::FETCH_UNIQUE);

See this example in the documentation.

0
mickmackusa On

Heed the warning from @YourCommonSense Is there a way to fetch associative array grouped by the values of a specified column with PDO?. Instead of using FETCH_GROUP, replace it with FETCH_UNIQUE, then you won't be bothered by the excess level in the payload.

Code: (PHPize Demo)

$stmt = $pdo->prepare($sql);
$stmt->execute();
var_export($stmt->fetchAll(PDO::FETCH_UNIQUE | PDO::FETCH_CLASS));