Skip to content

Instantly share code, notes, and snippets.

@grom358 grom358/obj_to_array.php
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.