[英]PHP recursively turning an ArrayObject to an Associative Array
Hey guys I have a method that is supposed to call back and recursively turn an Arrayobject
into an associative array, unfortunately I'm getting a fatal error 嗨我有一个应该再打一次,然后把递归的方法Arrayobject
进一个关联数组,不幸的是我发现了一个致命的错误
PHP Fatal error: Call to undefined method ArrayObject::toArray()
Here's my method 这是我的方法
/**
* Take an ArrayObject and recursively turn it into an array
*
* @param bool $recursion
*
* @return array
*/
public function toArray($recursion = false)
{
// just in case the object might be 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 a sample ArrayObject
这是一个示例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, by passing $this
as a variable I don't need to worry about colliding with $this->object
or scope issues. 通过将$this
作为变量传递,此方法可以正常工作,我不必担心与$this->object
或scope问题发生冲突。
/**
* Public wrapper for Protected getArray()
*
* @return arrau
*/
public function toArray()
{
return $this->getArray($this->object);
}
/**
* Take an ArrayObject and turn it into an associative array
*
* @param ArrayObject $obj
*
* @return array
*/
protected function getArray($obj)
{
$array = array(); // noisy $array does not exist
$arrObj = is_object($obj) ? get_object_vars($obj) : $obj;
foreach ($arrObj as $key => $val) {
$val = (is_array($val) || is_object($val)) ? $this->getArray($val) : $val;
$array[$key] = $val;
}
return $array;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.