1

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

1
  • Its an object oriented tool, get used to objects Commented Jan 12, 2018 at 14:22

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

above code returning this error : Warning: include_once(Query.php) [<a href='function.include-once'>function.include-once</a>]: failed to open stream: No such file or directory in /usr/local/zend/share/ZendFramework/library/Zend/Loader.php on line 134
@Ashfaq You have to import Query class. Check example above I have added use Doctrine\ORM\Query;.
Now, I am getting this error: Fatal error: Uncaught Doctrine\ORM\NonUniqueResultException in D:\xampp\htdocs\doctrine2\vendor\doctrine\orm\lib\Doctrine\ORM\AbstractQuery.php:774 after change $qb->getQuery()->getOneOrNullResult(Query::HYDRATE_ARRAY)
1

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.