php 如何将对象转换为数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2476876/
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 06:37:46  来源:igfitidea点击:

How do I convert an object to an array?

php

提问by zahir hussain

<?php
   print_r($response->response->docs);
?>

Outputs the following:

输出以下内容:

    Array 
(
    [0] => Object 
            (
                [_fields:private] => Array 
                                    (
                                        [id]=>9093 
                                        [name]=>zahir
                                    ) 
            Object 
            ( 
                [_fields:private] => Array 
                                    (
                                        [id]=>9094 
                                        [name]=>hussain
                                    )..
            )
)

How can I convert this object to an array? I'd like to output the following:

如何将此对象转换为数组?我想输出以下内容:

Array
(
    [0]=>
    (
        [id]=>9093 
        [name]=>zahir
    ) 
    [1]=>
    (
        [id]=>9094 
        [name]=>hussain
    )...
)

Is this possible?

这可能吗?

采纳答案by Benoit

You should look at get_object_vars, as your properties are declared private you should call this inside the class and return its results.

您应该查看get_object_vars,因为您的属性被声明为私有,您应该在类中调用它并返回其结果。

Be careful, for primitive data types like strings it will work great, but I don't know how it behaves with nested objects.

小心,对于像字符串这样的原始数据类型,它会很好用,但我不知道它对嵌套对象的行为如何。

in your case you have to do something like;

在您的情况下,您必须执行以下操作;

<?php
   print_r(get_object_vars($response->response->docs));
?>

回答by Andy E

Single-dimensional arrays

一维数组

For converting single-dimension arrays, you can cast using (array)or there's get_object_vars, which Benoit mentioned in his answer.

对于转换单维数组,您可以使用(array)或 there's 进行转换get_object_vars,Benoit 在他的回答中提到了这一点 。

// Cast to an array
$array = (array) $object;
// get_object_vars
$array = get_object_vars($object);

They work slightly different from each other. For example, get_object_varswill return an array with only publicly accessible properties unless it is called from within the scope of the object you're passing (ie in a member function of the object). (array), on the other hand, will cast to an array with all public, private and protected members intact on the array, though all public now, of course.

它们的工作原理略有不同。例如,get_object_vars将返回一个仅具有可公开访问属性的数组,除非它是在您传递的对象范围内(即在对象的成员函数中)调用的。 (array),另一方面,将转换为一个数组,该数组中的所有公共、私有和受保护成员都完好无损,当然,尽管现在都是公共成员。

Multi-dimensional arrays

多维数组

A somewhat dirty method is to use PHP >= 5.2's native JSON functions to encode to JSON and then decode back to an array. This will not include private and protected members, however, and is not suitable for objects that contain data that cannot be JSON encoded (such as binary data).

一个有点脏的方法是使用 PHP >= 5.2 的原生 JSON 函数编码为 JSON,然后解码回数组。但是,这将不包括私有成员和受保护成员,并且不适用于包含无法进行 JSON 编码的数据(例如二进制数据)的对象。

// The second parameter of json_decode forces parsing into an associative array
$array = json_decode(json_encode($object), true);

Alternatively, the following function will convert from an object to an array including private and protected members, taken from hereand modified to use casting:

或者,以下函数将从对象转换为包含私有和受保护成员的数组,取自此处并修改为使用强制转换:

function objectToArray ($object) {
    if(!is_object($object) && !is_array($object))
        return $object;

    return array_map('objectToArray', (array) $object);
}

回答by Mufaddal

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

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

$array = json_decode(json_encode($response->response->docs), true);

回答by Sergio

Careful:

小心:

$array = (array) $object;

does a shallow conversion ($object->innerObject = new stdClass() remains an object) and converting back and forth using json works but it's not a good idea if performance is an issue.

进行浅层转换($object->innerObject = new stdClass() 仍然是一个对象)并使用 json 来回转换有效,但如果性能有问题,这不是一个好主意。

If you need all objects to be converted to associative arrays here is a better way to do that (code ripped from I don't remember where):

如果您需要将所有对象转换为关联数组,这里是一个更好的方法(从我不记得从哪里撕下的代码):

function toArray($obj)
{
    if (is_object($obj)) $obj = (array)$obj;
    if (is_array($obj)) {
        $new = array();
        foreach ($obj as $key => $val) {
            $new[$key] = toArray($val);
        }
    } else {
        $new = $obj;
    }

    return $new;
}

回答by m3nda

$array = json_decode(json_encode($object), true);

I tried several ways to do a foreachwith an object and THIS really is the most easy and cool workaround I have seen. Just one line :)

我尝试了几种方法来foreach处理一个对象,这确实是我见过的最简单、最酷的解决方法。只有一行 :)

回答by Styx

Simple version:

简单版:

$arrayObject = new ArrayObject($object);
$array = $arrayObject->getArrayCopy();

Updated recursive version:

更新递归版本:

class RecursiveArrayObject extends ArrayObject
{
    function getArrayCopy()
    {
        $resultArray = parent::getArrayCopy();
        foreach($resultArray as $key => $val) {
            if (!is_object($val)) {
                continue;
            }
            $o = new RecursiveArrayObject($val);
            $resultArray[$key] = $o->getArrayCopy();
        }
        return $resultArray;
    }
}

$arrayObject = new RecursiveArrayObject($object);
$array = $arrayObject->getArrayCopy();

回答by kunal

Try this:-

尝试这个:-

 <?php
  print_r(json_decode(json_encode($response->response->docs),true));
 ?>

回答by Lucas Bacciotti

I had the same problem and I solved it with get_object_varsmentioned above.

我遇到了同样的问题,我用上面提到的get_object_vars解决了它。

Furthermore, I had to convert my object with json_decodeand I had to iterate the array with the oldschool "for" loop (rather then for-each).

此外,我必须使用json_decode转换我的对象,并且必须使用 oldschool“for”循环(而不是 for-each)迭代数组。

回答by Rikin Adhyapak

You can also use array_values() method of php

您也可以使用 php 的 array_values() 方法

回答by leon.clements

I ran into an issue with Andy Earnshaw's answer because I had factored this function out to a separate class within my application, "HelperFunctions", which meant the recursive call to objectToArray() failed.

我遇到了 Andy Earnshaw 的回答问题,因为我已将此函数分解为应用程序中的一个单独类“HelperFunctions”,这意味着对 objectToArray() 的递归调用失败。

I overcame this by specifying the class name within the array_map call like so:

我通过在 array_map 调用中指定类名来克服这个问题,如下所示:

public function objectToArray($object) {
    if (!is_object($object) && !is_array($object))
        return $object;
    return array_map(array("HelperFunctions", "objectToArray"), (array) $object);
}

I would have written this in the comments but I don't have enough reputation yet.

我会在评论中写下这个,但我还没有足够的声誉。