将PHP对象转换为关联数组 [英] Convert a PHP object to an associative array

查看:140
本文介绍了将PHP对象转换为关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个API集成到我的网站中,该网站可以使用数组编写代码时处理存储在对象中的数据.

I'm integrating an API to my website which works with data stored in objects while my code is written using arrays.

我想要一个快捷的函数来将对象转换为数组.

I'd like a quick-and-dirty function to convert an object to an array.

推荐答案

只需打字

$array = (array) $yourObject;

来自 数组 :

如果将对象转换为数组,则结果是一个数组,其元素是对象的属性.键是成员变量名称,但有一些值得注意的例外:整数属性不可访问;私有变量的类名在变量名之前;受保护的变量在变量名前带有"*".这些前置值的两边都为空字节.

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的输出:

Output with var_export instead of var_dump:

array (
  '' . "\0" . 'Foo' . "\0" . 'foo' => 1,
  '' . "\0" . '*' . "\0" . 'bar' => 2,
  'baz' =>
  stdClass::__set_state(array(
  )),
)

以这种方式进行类型转换不会对对象图进行深度转换,并且您需要应用空字节(如手册引用中所述)以访问任何非公共属性.因此,这在投射StdClass对象或仅具有公共属性的对象时效果最佳.对于快速又脏的(您要的),没关系.

Typecasting this way will not do deep casting of the object graph and you need to apply the null bytes (as explained in the manual quote) to access any non-public attributes. So this works best when casting StdClass objects or objects with only public properties. For quick and dirty (what you asked for) it's fine.

另请参阅此深入的博客文章:

Also see this in-depth blog post:

这篇关于将PHP对象转换为关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆