<?php
print_r($response->response->docs);
?>
Outputs the following:
Array
(
[0] => Object
(
[_fields:private] => Array
(
[id]=>9093
[name]=>zahir
)
Object
(
[_fields:private] => Array
(
[id]=>9094
[name]=>hussain
)..
)
)
How can I convert this object to an array? I'd like to output the following:
Array
(
[0]=>
(
[id]=>9093
[name]=>zahir
)
[1]=>
(
[id]=>9094
[name]=>hussain
)...
)
Is this possible?
You can also use array_values() method of php
You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:
Careful:
does a shallow conversion ($object->innerObject = new stdClass() remains an object) and converting back and forth using json works but it's not a good idea if performance is an issue.
If you need all objects to be converted to associative arrays here is a better way to do that (code ripped from I don't remember where):
I tried several ways to do a
foreach
with an object and THIS really is the most easy and cool workaround I have seen. Just one line :)Simple version:
Updated recursive version:
Single-dimensional arrays
For converting single-dimension arrays, you can cast using
(array)
or there'sget_object_vars
, which Benoit mentioned in his answer.They work slightly different from each other. For example,
get_object_vars
will return an array with only publicly accessible properties unless it is called from within the scope of the object you're passing (ie in a member function of the object).(array)
, on the other hand, will cast to an array with all public, private and protected members intact on the array, though all public now, of course.Multi-dimensional arrays
A somewhat dirty method is to use PHP >= 5.2's native JSON functions to encode to JSON and then decode back to an array. This will not include private and protected members, however, and is not suitable for objects that contain data that cannot be JSON encoded (such as binary data).
Alternatively, the following function will convert from an object to an array including private and protected members, taken from here and modified to use casting: