I'm integrating an API to my website which works with data stored in objects while my code is written using arrays.
I'd like a quick and dirty function to convert an object to an array.
I'm integrating an API to my website which works with data stored in objects while my code is written using arrays.
I'd like a quick and dirty function to convert an object to an array.
Also you can use The Symfony Serializer Component
Output
Here I've made an objectToArray() method, which also works with recursive objects, like when
$objectA
contains$objectB
which points again to$objectA
.Additionally I've restricted the output to public properties using ReflectionClass. Get rid of it, if you don't need it.
To identify already used objects, I am using a protected property in this (abstract) class, named
$this->usedObjects
. If a recursive nested object is found, it will be replaced by the string**recursive**
. Otherwise it would fail in because of infinite loop.Converting and removing annoying stars :
Probably, it will be cheaper than using reflections.
You might want to do this when you obtain data as objects from databases -->
To convert an object into array just cast it explicitly