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

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

问题描述

我正在将一个 API 集成到我的网站,该 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.

另见这篇深入的博文:

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

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