我正在集成一个API到我的网站,它与存储在对象中的数据一起工作,而我的代码是使用数组编写的。
我想要一个快速和肮脏的函数将对象转换为数组。
我正在集成一个API到我的网站,它与存储在对象中的数据一起工作,而我的代码是使用数组编写的。
我想要一个快速和肮脏的函数将对象转换为数组。
当前回答
这个答案只是这篇文章的不同答案的联合,但它是将具有简单值或数组的公有或私有属性的PHP对象转换为关联数组的解决方案…
function object_to_array($obj)
{
if (is_object($obj))
$obj = (array)$this->dismount($obj);
if (is_array($obj)) {
$new = array();
foreach ($obj as $key => $val) {
$new[$key] = $this->object_to_array($val);
}
}
else
$new = $obj;
return $new;
}
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;
}
其他回答
这是我的建议,如果你的对象中有私有成员的对象:
public function dismount($object) {
$reflectionClass = new \ReflectionClass(get_class($object));
$array = array();
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
if (is_object($property->getValue($object))) {
$array[$property->getName()] = $this->dismount($property->getValue($object));
} else {
$array[$property->getName()] = $property->getValue($object);
}
$property->setAccessible(false);
}
return $array;
}
get_object_vars($obj)怎么样?如果您只想访问对象的公共属性,它似乎很有用。
看到get_object_vars。
$Menu = new Admin_Model_DbTable_Menu();
$row = $Menu->fetchRow($Menu->select()->where('id = ?', $id));
$Addmenu = new Admin_Form_Addmenu();
$Addmenu->populate($row->toArray());
通过依赖JSON编码/解码函数的行为,可以快速将深度嵌套的对象转换为关联数组:
$array = json_decode(json_encode($nested_object), true);
首先,如果你需要一个来自对象的数组,你可能应该首先将数据构成一个数组。想想看。
不要使用foreach语句或JSON转换。如果您计划这样做,同样是在处理数据结构,而不是对象。
如果你真的需要它,可以使用面向对象的方法来获得干净和可维护的代码。例如:
对象作为数组
class PersonArray implements \ArrayAccess, \IteratorAggregate
{
public function __construct(Person $person) {
$this->person = $person;
}
// ...
}
如果你需要所有的属性,使用一个传输对象:
class PersonTransferObject
{
private $person;
public function __construct(Person $person) {
$this->person = $person;
}
public function toArray() {
return [
// 'name' => $this->person->getName();
];
}
}