Created
May 11, 2016 13:34
-
-
Save TwanoO67/50049affa4d0307d54dcdc527533269c to your computer and use it in GitHub Desktop.
Convert nested Object to associative array in php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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