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.
Custom Function to convert stdClass to array:
Another custom function to convert Array to stdClass:
Usage Example:
There's my proposal, if you have objects in objects with even private members:
returns array without special characters and class names
Just typecast it
From http://www.php.net/manual/en/language.types.array.php
Example: Simple Object
Output:
Example: Complex Object
Output (with \0s edited in for clarity):
Output with
var_export
instead ofvar_dump
:Typecasting this way will not do deep casting of the object graph and you need to apply the null bytes (as explained in the manual quote) to access any non-public attributes. So this works best when casting StdClass objects or objects with only public properties. For quick and dirty (what you asked for) it's fine.
Also see this in-depth blog post:
Since a lot of people find this thread because of having trouble with dynamically access attributes of an object, I will just point out that you can do this in php:
$valueRow->{"valueName"}
In Context (removed HTML output for readability):
What about
get_object_vars($obj)
? Seems useful if you only want to access the public properties of an object. http://www.php.net/function.get-object-vars