Is there a good way to convert a given object to an array?
spacesuitdiver opened this issue · 5 comments
Hello again,
I am trying to get the Google_Service_Calendar_Events object as an associative array OR get the underlying JSON response.
Is this possible?
Thanks for the help.
So the object that comes back implements arrayaccess, so you should be able to treat it like an array. What were you looking to do?
I did notice it implemented ArrayAccess afterward. The CMS I am building a module for requires an array and it'd be ideal if I didn't have to map the data in the object myself.
I tried type casting and that provided the first key but then the rest got cut off. Strangely passing $service['data']['items']
seems to work if I just want to pass in the items only, not the events collection metadata.
get_object_vars()
works but doesn't return the multidimensional data (such as items).
It'd be nice to be able to get the response somehow and be done with it.
Thanks for your response btw.
This iterative function runs through all the "getter" methods and crams the results into a multidimensional array. I'm sure this is like making fire with twig and twine but it seems to work:
function cl_object_to_array($object)
{
$result = array();
foreach(get_class_methods($object) as $method)
{
if (strpos($method, "get") === 0) {
$data = $object->$method();
if (is_object($data))
{
$result[lcfirst(substr($method, 3))] = cl_object_to_array($data);
}
elseif (is_array($data))
{
foreach ($data as $key => $value)
{
$result[lcfirst(substr($method, 3))][$key] = cl_object_to_array($value);
}
}
else
{
$result[lcfirst(substr($method, 3))] = $data;
}
}
}
return $result;
}
There is actually a broadly similar method in the library now. On the objects that get returned you can call toSimpleObject. This returns it as an object rather than an array, but it might be easier to translate that than the main method.
I like the idea of making a way of just getting the raw JSON though, which would be helpful for debugging if nothing else.
I'm going to track the raw JSON idea separately, so closing this one.