Back in July, I wrote an article about converting an object to array in PHP and mentioned the difficulties I was having with filtering private and protected keys to remove undesirable characters. I found a solution not long after, but never got around to writing a follow up. Here is my current function library to convert an object to an array, recursively, while maintaing nice keys.
< ?php
function convertObjectToArray(&$element) {
// the recursive call can't operate through objects, so they
// must be handled specially
if(is_object($element)) {
// typecast the object to an array, and clean up private and
// protected keys
$element = convertObjectToArray_keyCleanup((array)$element);
// begin the recursion again to go through this object-turned-array
// this is not strictly necesary, as removing it will cause the
// recursion to happen in convertToXml, but putting it here makes it
// more readable and ever so slightly faster.
array_walk_recursive(
$element,
'convertObjectToArray'
);
}
return $element;
}
function convertObjectToArray_keyCleanup($array) {
// find every invalid key (private and protected member properties)
foreach(array_filter(array_keys($array), 'convertObjectToArray_invalidKey')
as $invalidKey) {
// change the key name by copy / delete / create
$data = $array[$invalidKey];
unset($array[$invalidKey]);
// find out the correct key name by getting the last chunk that
// is only ascii 32 - 126, the standard set of printable characters
// User�Types => Types
$key = preg_replace(
'/^.*[^\x20-\x7E]([\x20-\x7E]*)$/',
'\\1',
$invalidKey
);
$array[$key] = $data;
}
return $array;
}
function convertObjectToArray_invalidKey($key) {
// a key is invalid if it has any characters that are outside
// of the ascii range 32 - 126, which is the standard set of printable
// characters
return preg_match('/[^\x20-\x7E]/', $key);
}
?>