简体   繁体   中英

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

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.

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.

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()];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM