oop - PHP recursively turning an ArrayObject to an Associative Array -
hey guys have method supposed call , recursively turn arrayobject associative array, unfortunately i'm getting fatal error
php fatal error: call undefined method arrayobject::toarray() here's method
/** * take arrayobject , recursively turn array * * @param bool $recursion * * @return array */ public function toarray($recursion = false) { // in case object might multidimensional if (true === $this->object) return $this->object->getarraycopy(); return array_map( function($item) { return is_object($item) ? $item->toarray(true) : $item; }, $this->object->getarraycopy() ); } and here's sample arrayobject
arrayobject object ( [storage:arrayobject:private] => array ( [profile] => arrayobject object ( [storage:arrayobject:private] => array ( [list] => arrayobject object ( [storage:arrayobject:private] => array ( [location] => [network_name] => [interests] => [last_name] => [url] => [significant_other] => [network_domains] => [contact] => arrayobject object ( [storage:arrayobject:private] => array ( [im] => arrayobject object ( [storage:arrayobject:private] => array ( [provider] => ) ) [email_addresses] => ) ) ) ) ) ) [messages] => arrayobject object ( [storage:arrayobject:private] => array ( [list] => array ( [0] => foo [1] => bar [2] => baz ) ) ) [groups] => arrayobject object ( [storage:arrayobject:private] => array ( ) ) [users] => arrayobject object ( [storage:arrayobject:private] => array ( ) ) ) )
this works correctly, passing $this variable don't need worry colliding $this->object or scope issues.
/** * public wrapper protected getarray() * * @return arrau */ public function toarray() { return $this->getarray($this->object); } /** * take arrayobject , turn associative array * * @param arrayobject $obj * * @return array */ protected function getarray($obj) { $array = array(); // noisy $array not exist $arrobj = is_object($obj) ? get_object_vars($obj) : $obj; foreach ($arrobj $key => $val) { $val = (is_array($val) || is_object($val)) ? $this->getarray($val) : $val; $array[$key] = $val; } return $array; }
Comments
Post a Comment