Jolan
Jolan

Reputation: 711

Doctrine - use column value as array index

I have this query:

$qb = $this
        ->_em
        ->createQueryBuilder();

    $qb
        ->select('f.name', 'f.id')
        ->from('Bundle:F', 'f', 'f.id');
    return $qb->getQuery()->getResult();

which returns the result like this:

array:438[▼
    214 => array:2[▼
       "name" => "xxx"
       "id" => 214
    ]
    215 => array:2[▼
       "name" => "yyy"
       "id" => 215
    ]
    ... 

But I don't want sub-arrays and want the result to be returned like this:

array:438[▼
    214 => "xxx"
    215 => "yyy"
    ...

i.e. id as the key and name as the value. Is that possible?

Upvotes: 3

Views: 1417

Answers (2)

Othman Mahmoud
Othman Mahmoud

Reputation: 153

$result =  $qb->getQuery()->getResult();
return array_column($result, "name", "id");

Upvotes: 2

Andreas
Andreas

Reputation: 23958

You can use and array_column to fix it in the array.

$arr = array_column($qb, "name", "id");  

This will isolate the id column and use that as key, and isolate name column and use that as values.

Upvotes: 3

Related Questions