Last active
August 29, 2015 14:19
-
-
Save grom358/f03924b26697c07d1d85 to your computer and use it in GitHub Desktop.
Convert PHP object to array
This file contains hidden or 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($data, $visited = array()) { | |
if (!is_array($data) and !is_object($data)) { | |
return $data; | |
} | |
if (is_object($data)) { | |
// Detect object cycles, overwise recursion occurs. | |
$hash = spl_object_hash($data); | |
if (isset($visited[$hash])) { | |
return '** RECURSION **'; | |
} | |
$visited[$hash] = TRUE; | |
$data = (array) $data; | |
} | |
$ret = array(); | |
foreach ($data as $key => $value) { | |
if (is_object($value) || is_array($value)) { | |
$value = object_to_array($value, $visited); | |
} | |
// Remove private and protected properties NULL delimited prefix. | |
if ($key[0] === "\x00") { | |
$property_name = substr($key, strpos($key, "\x0", 1)); | |
} | |
else { | |
$property_name = $key; | |
} | |
$ret[$property_name] = $value; | |
} | |
return $ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment