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

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

问题描述

我整合到我的网站,而我的code使用数组写入与存储在数据对象工作的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;

从<一个href=\"http://www.php.net/manual/en/language.types.array.php\">http://www.php.net/manual/en/language.types.array.php

如果一个对象被转换成一个阵列,其结果是一个数组,其元素为对象的属性。键是成员变量名,有几个明显的例外:整数属性不可访问;私有变量有ppended的变量名的类名$ P $;受保护的变量有ppended的变量名'*'$ P $。这些prepended值具有空字节两边。

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 );

输出(为清楚起见编辑在\\ 0):

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天全站免登陆