我正在集成一个API到我的网站,它使用存储在对象中的数据,而我的代码是使用数组编写的。
我想要一个快速实用的函数来将一个对象转换成一个数组。
发布于 2013-04-20 02:56:24
通过依赖JSON编码/解码函数的行为,您可以将深度嵌套的对象快速转换为关联数组:
$array = json_decode(json_encode($nested_object), true);
发布于 2013-04-16 03:48:21
如果您的对象属性是公共的,则可以执行以下操作:
$array = (array) $object;
如果它们是私有的或受保护的,它们在数组上会有奇怪的密钥名称。因此,在这种情况下,您将需要以下函数:
function dismount($object) {
$reflectionClass = new ReflectionClass(get_class($object));
$array = array();
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$array[$property->getName()] = $property->getValue($object);
$property->setAccessible(false);
}
return $array;
}
发布于 2011-09-20 23:33:25
下面是一些代码:
function object_to_array($data) {
if ((! is_array($data)) and (! is_object($data)))
return 'xxx'; // $data;
$result = array();
$data = (array) $data;
foreach ($data as $key => $value) {
if (is_object($value))
$value = (array) $value;
if (is_array($value))
$result[$key] = object_to_array($value);
else
$result[$key] = $value;
}
return $result;
}
https://stackoverflow.com/questions/4345554
复制相似问题