Doctrine 2: Query result as associative array

Yeroon picture Yeroon · Dec 22, 2012 · Viewed 48.2k times · Source

In my Repository class I use the following code to query:

$query = $this->getEntityManager()->createQuery("
    SELECT s.term, COUNT(s.term) AS freq
    FROM App\Entities\SearchTerm s
    GROUP BY s.term
    ORDER BY s.term ASC
");

$result = $query->getResult();

The result I get is something like:

array (size=4)
  0 => 
    array (size=2)
      'term' => string '' (length=0)
      'freq' => string '1' (length=1)
  1 => 
    array (size=2)
      'term' => string 'foo' (length=3)
      'freq' => string '1' (length=1)
  2 => 
    array (size=2)
      'term' => string 'bar' (length=3)
      'freq' => string '2' (length=1)
  3 => 
    array (size=2)
      'term' => string 'baz' (length=3)
      'freq' => string '2' (length=1)

But I would rather have an associative array as a result:

array (size=4)
  '' => string '1' (length=1)
  'foo' => string '1' (length=1)
  'bar' => string '2' (length=1)
  'baz' => string '2' (length=1)

Is this possible without an extra for-loop to build the desired array?

Answer

Axidepuy picture Axidepuy · Jul 22, 2013

I know its old but today I had to do almost the same, my solution without a custom hydrator

  • INDEX BY s.term
  • modify the getResult() to be sure

like

$result = $query->getQuery()->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
  • format the result

as

$resultNeeded = array_map(function($value) { return $value['freq']; }, $result);