Without delay here's the Flatr function:
// Example structure
$obj = new stdClass();
$obj->prop1 = 'hello';
$obj->prop2 = new stdClass();
$obj->prop2->prop2 = 'there';
$obj->prop2->prop3 = 'world!';
/**
*
* @param stdClass $obj
* @return array
*/
function flatr($obj) {
$ret = array();
$recursiveWalk = function( $baseObject ) use (&$recursiveWalk, &$ret) {
if (is_object($baseObject)) {
foreach($baseObject as $propValue) $recursiveWalk($propValue);
} else {
$ret[] = $baseObject;
}
};
$recursiveWalk($obj);
return $ret;
}
var_dump(flatr($obj));
This will output:
array(3) { [0]=> string(5) "hello" [1]=> string(5) "there" [2]=> string(6) "world!" }
This little function is not ready to handle arrays inside the object structure. But the required changes are not hard to make.
Next post I'll demonstrate a practical usage for this function.
No comments:
Post a Comment