将 PHP 对象转换为关联数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4345554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:44:41  来源:igfitidea点击:

Convert a PHP object to an associative array

phparrays

提问by Haroldo

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

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

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

我想要一个快速而肮脏的函数来将对象转换为数组。

回答by Gordon

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) {
  '
array (
  '' . "
$array = json_decode(json_encode($nested_object), true);
" . 'Foo' . "
function object_to_array($data)
{
    if (is_array($data) || is_object($data))
    {
        $result = array();
        foreach ($data as $key => $value)
        {
            $result[$key] = object_to_array($value);
        }
        return $result;
    }
    return $data;
}
" . 'foo' => 1, '' . "
$array =  (array) $object;
" . '*' . "
function dismount($object) {
    $reflectionClass = new ReflectionClass(get_class($object));
    $array = array();
    foreach ($reflectionClass->getProperties() as $property) {
        $property->setAccessible(true);
        $array[$property->getName()] = $property->getValue($object);
        $property->setAccessible(false);
    }
    return $array;
}
" . 'bar' => 2, 'baz' => stdClass::__set_state(array( )), )
Foo
class Test{
    const A = 1;
    public $b = 'two';
    private $c = test::A;

    public function __toArray(){
        return call_user_func('get_object_vars', $this);
    }
}

$my_test = new Test();
var_dump((array)$my_test);
var_dump($my_test->__toArray());
foo' => int(1) '
array(2) {
    ["b"]=>
    string(3) "two"
    ["Testc"]=>
    int(1)
}
array(1) {
    ["b"]=>
    string(3) "two"
}
*
function object_to_array($data) {
    if ((! is_array($data)) and (! is_object($data)))
        return 'xxx'; // $data;

    $result = array();

    $data = (array) $data;
    foreach ($data as $key => $value) {
        if (is_object($value))
            $value = (array) $value;
        if (is_array($value))
            $result[$key] = object_to_array($value);
        else
            $result[$key] = $value;
    }
    return $result;
}
bar' => int(2) 'baz' => class stdClass#2 (0) {} }

Output with var_exportinstead of var_dump:

输出var_export而不是var_dump

function entity2array($entity, $recursionDepth = 2) {
    $result = array();
    $class = new ReflectionClass(get_class($entity));
    foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
        $methodName = $method->name;
        if (strpos($methodName, "get") === 0 && strlen($methodName) > 3) {
            $propertyName = lcfirst(substr($methodName, 3));
            $value = $method->invoke($entity);

            if (is_object($value)) {
                if ($recursionDepth > 0) {
                    $result[$propertyName] = $this->entity2array($value, $recursionDepth - 1);
                }
                else {
                    $result[$propertyName] = "***";  // Stop recursion
                }
            }
            else {
                $result[$propertyName] = $value;
            }
        }
    }
    return $result;
}

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.

以这种方式进行类型转换不会对对象图进行深度转换,您需要应用空字节(如手册引用中所述)来访问任何非公共属性。因此,这在转换 StdClass 对象或仅具有公共属性的对象时效果最佳。对于快速和肮脏(您要求的),这很好。

Also see this in-depth blog post:

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

回答by Jeff Standen

You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:

通过依赖 JSON 编码/解码函数的行为,您可以快速将深度嵌套的对象转换为关联数组:

$arr =  (array) $Obj;

回答by Maurycy

From the first Google hit for "PHP object to assoc array" we have this:

从第一次 Google 搜索“ PHP object to assoc array”开始,我们有这个:

class PersonArray implements \ArrayAccess, \IteratorAggregate
{
    public function __construct(Person $person) {
        $this->person = $person;
    }
    // ...
 }

The source is at codesnippets.joyent.com.

来源位于 codenippets.joyent.com

回答by Ramon K.

If your object properties are public you can do:

如果您的对象属性是公开的,您可以执行以下操作:

class PersonTransferObject
{
    private $person;

    public function __construct(Person $person) {
        $this->person = $person;
    }

    public function toArray() {
        return [
            // 'name' => $this->person->getName();
        ];
    }

 }

If they are private or protected, they will have weird key names on the array. So, in this case you will need the following function:

如果它们是私有的或受保护的,它们将在数组上有奇怪的键名。因此,在这种情况下,您将需要以下功能:

##代码##

回答by Isius

##代码##

Output

输出

##代码##

回答by Khalid

Here is some code:

这是一些代码:

##代码##

回答by Francois Bourgeois

All other answers posted here are only working with public attributes. Here is one solution that works with JavaBeans-like objects using reflection and getters:

此处发布的所有其他答案仅适用于公共属性。这是一种使用反射和 getter与JavaBeans类对象一起使用的解决方案:

##代码##

回答by Joe

What about get_object_vars($obj)? It seems useful if you only want to access the public properties of an object.

怎么样get_object_vars($obj)?如果您只想访问对象的公共属性,这似乎很有用。

See get_object_vars.

请参阅get_object_vars

回答by Adeel

Type cast your object to an array.

将您的对象类型转换为数组。

##代码##

It will solve your problem.

它会解决你的问题。

回答by John Smith

First of all, if you need an array from an object you probably should constitute the data as an array first. Think about it.

首先,如果您需要来自对象的数组,您可能应该首先将数据构造为数组。想想看。

Don't use a foreachstatement or JSON transformations. If you're planning this, again you're working with a data structure, not with an object.

不要使用foreach语句或 JSON 转换。如果您正在计划此操作,那么您再次使用的是数据结构,而不是对象。

If you really need it use an object-oriented approach to have a clean and maintainable code. For example:

如果您真的需要它,请使用面向对象的方法来拥有干净且可维护的代码。例如:

Object as array

对象作为数组

##代码##

If you need all properties, use a transfer object:

如果您需要所有属性,请使用传输对象:

##代码##