Skip to content

Instantly share code, notes, and snippets.

@TwanoO67
Created May 11, 2016 13:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TwanoO67/50049affa4d0307d54dcdc527533269c to your computer and use it in GitHub Desktop.
Save TwanoO67/50049affa4d0307d54dcdc527533269c to your computer and use it in GitHub Desktop.
Convert nested Object to associative array in php
<?php
function object_to_array($obj) {
if(is_object($obj)) $obj = (array) dismount($obj);
if(is_array($obj)) {
$new = array();
foreach($obj as $key => $val) {
$new[$key] = object_to_array($val);
}
}
else $new = $obj;
return $new;
}
function dismount($object) {
$reflectionClass = new ReflectionClass(get_class($object));
$array = array();
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$array[$property->getName()] = $property->getValue($object);
$property->setAccessible(false);
}
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment