I'm using Doctrine 2 ORM to map my SQL table into objects.
Is there a support method like asArray
which converts my objects into an array?

- 41,477
- 12
- 152
- 203

- 511
- 6
- 18
-
1Possible duplicate of [Doctrine entity object to array](http://stackoverflow.com/questions/25158549/doctrine-entity-object-to-array) – Joucks Jan 31 '17 at 09:57
-
Didn't see any solution in that topic :( – Matteo Martinelli Jan 31 '17 at 10:28
-
Which php framework are you using? – Wilt Jan 31 '17 at 11:07
-
I'm not using any framework – Matteo Martinelli Jan 31 '17 at 14:41
1 Answers
You can simply use the getArrayResult
method that is mentioned here inside the Doctrine 2 documentation chapter 14.7.4.2. Array Hydration:
$array = $query->getArrayResult();
It is a short notation for, and does exactly the same as, this answer that that @Joucks is pointing to in his comment:
$array = $query->getResult(Query::HYDRATE_ARRAY);
But you don't necessarily have to look at specific Doctrine ORM solutions for such serializing functionality. You could also look at solutions that come with the PHP framework that you are using.
Zend-Framework
For example if you use Zend-Framework you could implement the ArraySerializableInterface
inside the objects that you want to be able to serialize to an array.
This interface includes an getArrayCopy
method that should return the object serialized to an array.
You can read more about ArraySerializable
inside the Zend-Framework 2 Zend\Stdlib
documentation
Symfony
Symfony ships with this Serializer component.
For other frameworks I expect they are shipped with similar interfaces/solutions.