我正在将一个 API 集成到我的网站中,该 API 可以处理存储在对象中的数据,而我的代码是使用数组编写的。
我想要一个快速而简单的函数来将对象转换为数组。
最佳答案
只是打字
$array = (array) $yourObject;
来自 Arrays :
If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.
示例:简单对象
$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
输出:
array(2) {
'foo' => int(1)
'bar' => int(2)
}
示例:复杂对象
class Foo
{
private $foo;
protected $bar;
public $baz;
public function __construct()
{
$this->foo = 1;
$this->bar = 2;
$this->baz = new StdClass;
}
}
var_dump( (array) new Foo );
输出(为清楚起见编辑了\0s):
array(3) {
'\0Foo\0foo' => int(1)
'\0*\0bar' => int(2)
'baz' => class stdClass#2 (0) {}
}
用 var_export
代替 var_dump
输出:
array (
'' . "\0" . 'Foo' . "\0" . 'foo' => 1,
'' . "\0" . '*' . "\0" . 'bar' => 2,
'baz' =>
stdClass::__set_state(array(
)),
)
以这种方式进行类型转换不会对对象图进行深度转换,您需要应用空字节(如手册引用中所述)来访问任何非公共(public)属性。因此,这在转换 StdClass 对象或仅具有公共(public)属性的对象时效果最佳。对于快速和肮脏的(你要求的)它很好。
另请参阅这篇深入的博文:
关于php - 将 PHP 对象转换为关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4345554/