Reputation: 269
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
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
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
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