Ashfaq
Ashfaq

Reputation: 269

How to get a Doctrine 2 result as an associative array?

I want to get the results in array for this code:

 $person = $em->find('Person', 2);

I am using doctrine 2. I want the above result in array form. .

PHP version 5.4

Upvotes: 1

Views: 1737

Answers (3)

bliszka
bliszka

Reputation: 68

The best approach is to write method in your Repository class or create query builder inline (but it is not recommended).

use Doctrine\ORM\Query;


...


$qb = $em->getRepository(Person::class)->createQueryBuilder('p');
$qb
   ->andWhere('p.id = :id')
   ->setParameter('id', $id)
;

$person = $qb->getQuery()->getResult(Query::HYDRATE_ARRAY);

Replace

$qb->getQuery()->getResult(Query::HYDRATE_ARRAY)

by

$qb->getQuery()->getOneOrNullResult(Query::HYDRATE_ARRAY)

if you need to get only one element.

Upvotes: 2

Ashfaq Muhammad
Ashfaq Muhammad

Reputation: 790

I have found a solution :

$person = $em->find('Person', 2);
$personx = json_decode(json_encode((array)$person), true);

echo '<pre>';
print_r($personx);
echo '<pre>'; 

It is working perfectly for me.

Upvotes: 1

Eugene Nikolaev
Eugene Nikolaev

Reputation: 79

As $person may be object with circular references, it can not be converted to array directly, but you can use serializing, like it described here Symfony Serialize doctrine entity

Or you can do it manually:

$person_array = ['name' => $person->getName(), 'id' => $person->getId()];

Upvotes: 0

Related Questions