Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to keep unique index in result array using PHP PDO::FETCH_UNIQUE?

I'm using the following PDO statement with the PDO::FETCH_UNIQUE flag to make the result array indexed by the unique row ID.

<?php
    $statement = $conn->prepare("
        SELECT
            unique_id, field_1, field_2, field_3
        FROM
            table
        WHERE
                field_1 = 'foo'
            AND field_2 = ?
        ORDER BY
            field_3
    ");

    if($statement->execute(array($field_2_value)))
    {
        $resultArray = $statement->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_UNIQUE);
    }
?>

$resultArray:

Array
(
    [123] => Array
        (
            [field_1] => foo
            [field_2] => someVal
            [field_3] => bar
        )
    [234] => Array
        (
            [field_1] => foo
            [field_2] => someVal
            [field_3] => car
        )
    [345] => Array
        (
            [field_1] => foo
            [field_2] => someVal
            [field_3] => dog
        )
)

Is there a way to keep both the array indexes as they are and retain the unique row ID in the row data like this:

 Array
(
    [123] => Array
        (
            [unique_id] => 123
            [field_1] => foo
            [field_2] => someVal
            [field_3] => bar
        )
    [234] => Array
        (
            [unique_id] => 234
            [field_1] => foo
            [field_2] => someVal
            [field_3] => car
        )
    [345] => Array
        (
            [unique_id] => 345
            [field_1] => foo
            [field_2] => someVal
            [field_3] => dog
        )
)

I realise I could do this with a secondary loop but it would feel a lot cleaner if this was an option in fetchAll().

like image 385
bbeckford Avatar asked Oct 18 '25 16:10

bbeckford


1 Answers

Yes, it perfectly possible, as you can always add an extra field to the field list.

$statement = $conn->prepare("
    SELECT
        unique_id uid, unique_id, field_1, field_2, field_3
    FROM
        table
    WHERE
            field_1 = 'foo'
        AND field_2 = ?
    ORDER BY
        field_3
");

and have your unique_id among values.

However, I don't think it's quite necessary as you can always get an index from foreach as it mentioned in the other answer.

like image 76
Your Common Sense Avatar answered Oct 21 '25 06:10

Your Common Sense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!