10
$shops = $this->em->getRepository('models\Shop')->findAll();

Gives my an array with entities but I need the entity as array.

How do I convert an entity to an array?

1
  • entity as array How does entity look like and how would the array look like? Commented Nov 25, 2011 at 14:01

2 Answers 2

16

Doctrine allows you to specify a hydration mode when executing queries, which let's you change the data type of the results returned. In this case, you need Query::HYDRATE_ARRAY. It does not let you specify this on the default findAll() method, found on the repositories. You will need to write your own DQL for it.

If you need a collection of entites as arrays:

$query = $em->createQuery('SELECT u FROM User u');
$entites = $query->execute(array(), Query::HYDRATE_ARRAY);

// If you don't have parameters in the query, you can use the getResult() shortcut
$query = $em->createQuery('SELECT u FROM User u');
$entities = $query->getResult(Query::HYDRATE_ARRAY);

If you need a single entity as an array, eg. for a specific ID:

$query = $em->createQuery('SELECT u FROM User u WHERE u.id = ?1');
$query->setParameter(1, $id);
$entity = $query->getSingleResult(Query::HYDRATE_ARRAY);

These methods are defined on Query, and AbstractQuery.

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

1 Comment

But that makes it unpossible to use with the abstract EntityRepository->findAll() method.
12

I had the same issue.return get_object_vars($this) is not a good solution because it also converts internal doctrine object/properties too.After some research i found this class: EntitySerializer which creates clean array or JSON from your entities and removes unnecessary items.The documentation is located here.For example i used the following code:

$patientProfile = $this->em->getRepository('Entities\Patientprofile')->findOneByuserid('2222222');
$entitySerializer=new Bgy\Doctrine\EntitySerializer($this->em);
$patientProfile=$entitySerializer->toArray($patientProfile);

1 Comment

How install it in Zend Framework 2? Can you explain like for idiot? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.