Better way to create associative array from Doctrine resultset

I'm often making simple loops like this to map a single value from a Doctrine resultset to a id->value mapped array:

            $rows = $this->em->getRepository(Tag::class)->findAll();
            $result = [];
            foreach ($rows as $row) {
                $result[$row->getId()] = $row->getName();
            }

I remember seeing an example of a simpler way to do this, with an array function like array_map maybe..but can't figure it out. Anyone got a way to do this with less code?


Solution 1:

I think what you need is doctrine's INDEX_BY

By default a result is incremented by numerical keys starting with 0. However with INDEX BY you can specify any other column to be the key of your result, it really only makes sense with primary or unique fields though

$query = $this->em->getRepository(Tag::class)
                  ->createQueryBuilder('t')
                  ->indexBy('t', 't.id');
$result = $query
->getQuery()
->getResult();