Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

php - 将PHP对象转换为关联数组(Convert a PHP object to an associative array)

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

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

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

(我想要一个快捷方式将对象转换为数组的函数。)

  ask by Haroldo translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just typecast it

(只是打字)

$array = (array) $yourObject;

From 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.

(这些前置值的任一侧都有空字节。)

Example: Simple Object

(示例:简单对象)

$object = new StdClass;
$object->foo = 1;
$object->bar = 2;

var_dump( (array) $object );

Output:

(输出:)

array(2) {
  'foo' => int(1)
  'bar' => int(2)
}

Example: Complex Object

(示例:复杂对象)

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

Output (with \0s edited in for clarity):

(输出(为清晰起见,已编辑\ 0s):)

array(3) {
  'Foofoo' => int(1)
  '*bar' => int(2)
  'baz' => class stdClass#2 (0) {}
}

Output with var_export instead of var_dump :

(使用var_export而不是var_dump输出:)

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

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.

(因此,这在投射StdClass对象或仅具有公共属性的对象时效果最佳。)

For quick and dirty (what you asked for) it's fine.

(为了快速又肮脏(您想要的),这很好。)

Also see this in-depth blog post:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...