1

My database table looks like this;

id   name
---------
1    Open
2    On Hold
3    Closed

the result i want is an associative array like this;

array(1 => 'Open', 2 => 'On hold', 3 => 'Closed');

I can't find any simple way to return these results from doctine, so I'm using this code;

$query = $this->em->createQuery("SELECT s FROM Project\Entity\ProjectStatus s");
$statuses = $query->getResult();
$result = array();
foreach($statuses as $status)
{
    $result[$status->getId()] = $status->getName();
}
return $result;

This feels long winded. Is there a simpler way? I've tried Query::HYDRATE_ARRAY but it still includes the field names in the resulting array. I just wan't the values.

srayner
  • 1,799
  • 4
  • 23
  • 39
  • Possible duplicate of [Doctrine 2: Query result as associative array](http://stackoverflow.com/questions/14002888/doctrine-2-query-result-as-associative-array) – jayxhj Dec 02 '15 at 14:07
  • Any success with my answer? Or is it not working? – Wilt Dec 08 '15 at 09:26

1 Answers1

0

This has been answered before
As of PHP 5.5 you can use array_column to solve this

$queryBuilder = $this->createQueryBuilder('s')
    ->select('s.name');
$query = $queryBuilder->getQuery();

or

$query = $this->em->createQuery("SELECT s.name FROM Project\Entity\ProjectStatus s");

and then

$result = $query->getArrayResult();
$names = array_column($result, 'name');

Use s.name, there is no need to get the whole ProjectStatus if you only need the name.

Community
  • 1
  • 1
Wilt
  • 41,477
  • 12
  • 152
  • 203