php - 将 PHP 对象转换为关联数组

标签 php arrays

我正在将一个 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/

相关文章:

C++ 程序在非预期输入时挂起

c++ - 在使用数组时使用 vector 容器挂起可快速计算2D数组

javascript - Javascript 是否可以使用可变长度数组

php - 使用正则表达式获取文本开头的 # 个字符

php - 如何在mysql中管理并发?

arrays - 通过向前移动其他元素来改变数组中元素的位置 - NumPy

java - 大字节数组使用的堆比预期多

PHP 发布和条件错误

php - 无法检查查询是否返回行

php - 从小到大排序