In PHP, you can easily convert an object to an array by typecasting it.
$array = (array) $object;
But if you have multi-dimensional / nested objects, this will only converts the top level of the object. So instead of looping through the object and typecasting it, just use this single line code:
$array = json_decode(json_encode($object), true);
And to convert an array to an object recursively:
$object = json_decode(json_encode($array, JSON_FORCE_OBJECT), false);
note: This only works if the properties of the object you are trying to convert are declared as public