Skip to content

Instantly share code, notes, and snippets.

@grom358
Last active August 29, 2015 14:19
Show Gist options
  • Save grom358/f03924b26697c07d1d85 to your computer and use it in GitHub Desktop.
Save grom358/f03924b26697c07d1d85 to your computer and use it in GitHub Desktop.
Convert PHP object to array
<?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