简体   繁体   English

将 PHP object 转换为关联数组

[英]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 集成到我的网站,该网站使用存储在对象中的数据,而我的代码是使用 arrays 编写的。

I'd like a quick-and-dirty function to convert an object to an array.我想要一个快速而肮脏的 function 将 object 转换为数组。

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) {
  '\0Foo\0foo' => int(1)
  '\0*\0bar' => int(2)
  'baz' => class stdClass#2 (0) {}
}

Output with var_export instead of var_dump :使用var_export而不是var_dump输出:

array (
  '' . "\0" . 'Foo' . "\0" . 'foo' => 1,
  '' . "\0" . '*' . "\0" . '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:另请参阅这篇深入的博客文章:

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

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

From the first Google hit for " PHP object to assoc array " we have this:从第一次 Google 搜索“ PHP object to assoc array ”开始,我们有这个:

function object_to_array($data)
{
    if (is_array($data) || is_object($data))
    {
        $result = [];
        foreach ($data as $key => $value)
        {
            $result[$key] = (is_array($data) || is_object($data)) ? object_to_array($value) : $value;
        }
        return $result;
    }
    return $data;
}

The source is at codesnippets.joyent.com .来源位于 codenippets.joyent.com


To compare it to the solution of json_decode & json_encode , this one seems faster.将其与json_decode & json_encode的解决方案进行比较,这个解决方案似乎更快。 Here is a random benchmark (using the simple time measuring ):这是一个随机基准(使用简单的时间测量):

$obj = (object) [
    'name'    =>'Mike',
    'surname' =>'Jovanson',
    'age'     =>'45',
    'time'    =>1234567890,
    'country' =>'Germany',
];

##### 100 000 cycles ######
* json_decode(json_encode($var))   : 4.15 sec
* object_to_array($var)            : 0.93 sec

If your object properties are public you can do:如果您的对象属性是公开的,您可以执行以下操作:

$array =  (array) $object;

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:因此,在这种情况下,您将需要以下功能:

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

What about get_object_vars($obj) ? get_object_vars($obj)呢? It seems useful if you only want to access the public properties of an object.如果您只想访问对象的公共属性,这似乎很有用。

See get_object_vars .请参阅get_object_vars

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

Output输出

array(2) {
    ["b"]=>
    string(3) "two"
    ["Testc"]=>
    int(1)
}
array(1) {
    ["b"]=>
    string(3) "two"
}

Here is some code:这是一些代码:

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

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类对象一起使用的解决方案:

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

Type cast your object to an array.将您的对象类型转换为数组。

$arr =  (array) $Obj;

It will solve your problem.它会解决你的问题。

Use:用:

function readObject($object) {
    $name = get_class ($object);
    $name = str_replace('\\', "\\\\", $name); // Outcomment this line, if you don't use
                                              // class namespaces approach in your project
    $raw = (array)$object;

    $attributes = array();
    foreach ($raw as $attr => $val) {
        $attributes[preg_replace('('.$name.'|\*|)', '', $attr)] = $val;
    }
    return $attributes;
}

It returns an array without special characters and class names.它返回一个没有特殊字符和类名的数组。

要将对象转换为数组,只需显式转换它:

$name_of_array = (array) $name_of_object;

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 foreach statement or JSON transformations.不要使用foreach语句或 JSON 转换。 If you're planning this, again you're working with a data structure, not with an object.如果您正在计划此操作,那么您再次使用的是数据结构,而不是对象。

If you really need it use an object-oriented approach to have a clean and maintainable code.如果您真的需要它,请使用面向对象的方法来拥有干净且可维护的代码。 For example:例如:

Object as array对象作为数组

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

If you need all properties, use a transfer object:如果您需要所有属性,请使用传输对象:

class PersonTransferObject
{
    private $person;

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

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

 }

You can easily use this function to get the result:您可以轻松地使用此函数来获得结果:

function objetToArray($adminBar){
    $reflector = new ReflectionObject($adminBar);
    $nodes = $reflector->getProperties();
    $out = [];
    foreach ($nodes as $node) {
        $nod = $reflector->getProperty($node->getName());
        $nod->setAccessible(true);
        $out[$node->getName()] = $nod->getValue($adminBar);
    }
    return $out;
}

Use PHP 5 or later.使用PHP 5或更高版本。

Here is my recursive PHP function to convert PHP objects to an associative array:这是我将 PHP 对象转换为关联数组的递归 PHP 函数:

// ---------------------------------------------------------
// ----- object_to_array_recursive --- function (PHP) ------
// ---------------------------------------------------------
// --- arg1: -- $object  =  PHP Object         - required --
// --- arg2: -- $assoc   =  TRUE or FALSE      - optional --
// --- arg3: -- $empty   =  '' (Empty String)  - optional --
// ---------------------------------------------------------
// ----- Return: Array from Object --- (associative) -------
// ---------------------------------------------------------

function object_to_array_recursive($object, $assoc=TRUE, $empty='')
{
    $res_arr = array();

    if (!empty($object)) {

        $arrObj = is_object($object) ? get_object_vars($object) : $object;

        $i=0;
        foreach ($arrObj as $key => $val) {
            $akey = ($assoc !== FALSE) ? $key : $i;
            if (is_array($val) || is_object($val)) {
                $res_arr[$akey] = (empty($val)) ? $empty : object_to_array_recursive($val);
            }
            else {
                $res_arr[$akey] = (empty($val)) ? $empty : (string)$val;
            }
            $i++;
        }
    }
    return $res_arr;
}

// ---------------------------------------------------------
// ---------------------------------------------------------

Usage example:用法示例:

// ---- Return associative array from object, ... use:
$new_arr1 = object_to_array_recursive($my_object);
// -- or --
// $new_arr1 = object_to_array_recursive($my_object, TRUE);
// -- or --
// $new_arr1 = object_to_array_recursive($my_object, 1);


// ---- Return numeric array from object, ... use:
$new_arr2 = object_to_array_recursive($my_object, FALSE);

You can also create a function in PHP to convert an object array:您还可以在 PHP 中创建一个函数来转换对象数组:

function object_to_array($object) {
    return (array) $object;
}

You might want to do this when you obtain data as objects from databases:当您从数据库中获取作为对象的数据时,您可能希望这样做:

// Suppose 'result' is the end product from some query $query

$result = $mysqli->query($query);
$result = db_result_to_array($result);

function db_result_to_array($result)
{
    $res_array = array();

    for ($count=0; $row = $result->fetch_assoc(); $count++)
        $res_array[$count] = $row;

    return $res_array;
}

Custom function to convert stdClass to an array:将 stdClass 转换为数组的自定义函数:

function objectToArray($d) {
    if (is_object($d)) {
        // Gets the properties of the given object
        // with get_object_vars function
        $d = get_object_vars($d);
    }

    if (is_array($d)) {
        /*
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        */
        return array_map(__FUNCTION__, $d);
    } else {
        // Return array
        return $d;
    }
}

Another custom function to convert Array to stdClass:另一个将 Array 转换为 stdClass 的自定义函数:

function arrayToObject($d) {
    if (is_array($d)) {
        /*
        * Return array converted to object
        * Using __FUNCTION__ (Magic constant)
        * for recursive call
        */
        return (object) array_map(__FUNCTION__, $d);
    } else {
        // Return object
        return $d;
    }
}

Usage Example:用法示例:

// Create new stdClass Object
$init = new stdClass;

// Add some test data
$init->foo = "Test data";
$init->bar = new stdClass;
$init->bar->baaz = "Testing";
$init->bar->fooz = new stdClass;
$init->bar->fooz->baz = "Testing again";
$init->foox = "Just test";

// Convert array to object and then object back to array
$array = objectToArray($init);
$object = arrayToObject($array);

// Print objects and array
print_r($init);
echo "\n";
print_r($array);
echo "\n";
print_r($object);

This answer is only the union of the different answers of this post, but it's the solution to convert a PHP object with public or private properties with simple values or arrays to an associative array...这个答案只是这篇文章不同答案的结合,但它是将具有公共或私有属性的 PHP 对象与简单的值或数组转换为关联数组的解决方案......

function object_to_array($obj)
{
    if (is_object($obj))
        $obj = (array)$this->dismount($obj);
    if (is_array($obj)) {
        $new = array();
        foreach ($obj as $key => $val) {
            $new[$key] = $this->object_to_array($val);
        }
    }
    else
        $new = $obj;
    return $new;
}

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

Converting and removing annoying stars:转换和删除烦人的星星:

$array = (array) $object;
foreach($array as $key => $val)
{
    $new_array[str_replace('*_', '', $key)] = $val;
}

Probably, it will be cheaper than using reflections.也许,它会比使用反射便宜。

Some impovements to the "well-knwon" code对“众所周知的”代码的一些改进

/*** mixed Obj2Array(mixed Obj)***************************************/ 
static public function Obj2Array($_Obj) {
    if (is_object($_Obj))
        $_Obj = get_object_vars($_Obj);
    return(is_array($_Obj) ? array_map(__METHOD__, $_Obj) : $_Obj);   
} // BW_Conv::Obj2Array

Notice that if the function is member of a class (like above) you must change __FUNCTION__ to __METHOD__请注意,如果函数是类的成员(如上),则必须将__FUNCTION__更改为__METHOD__

Short solution of @SpYk3HH @SpYk3HH 的简短解决方案

function objectToArray($o)
{
    $a = array();
    foreach ($o as $k => $v)
        $a[$k] = (is_array($v) || is_object($v)) ? objectToArray($v): $v;

    return $a;
}

Also you can use The Symfony Serializer Component你也可以使用Symfony Serializer 组件

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$array = json_decode($serializer->serialize($object, 'json'), true);

For your case it was right/beautiful if you would use the "decorator" or "date model transformation" patterns.对于您的情况,如果您使用“装饰器”或“日期模型转换”模式,那是正确/美丽的。 For example:例如:

Your model你的模特

class Car {
    /** @var int */
    private $color;

    /** @var string */
    private $model;

    /** @var string */
    private $type;

    /**
     * @return int
     */
    public function getColor(): int
    {
        return $this->color;
    }

    /**
     * @param int $color
     * @return Car
     */
    public function setColor(int $color): Car
    {
        $this->color = $color;
        return $this;
    }

    /**
     * @return string
     */
    public function getModel(): string
    {
        return $this->model;
    }

    /**
     * @param string $model
     * @return Car
     */
    public function setModel(string $model): Car
    {
        $this->model = $model;

        return $this;
    }

    /**
     * @return string
     */
    public function getType(): string
    {
        return $this->type;
    }

    /**
     * @param string $type
     * @return Car
     */
    public function setType(string $type): Car
    {
        $this->type = $type;

        return $this;
    }
}

Decorator装饰器

class CarArrayDecorator
{
    /** @var Car */
    private $car;

    /**
     * CarArrayDecorator constructor.
     * @param Car $car
     */
    public function __construct(Car $car)
    {
        $this->car = $car;
    }

    /**
     * @return array
     */
    public function getArray(): array
    {
        return [
            'color' => $this->car->getColor(),
            'type' => $this->car->getType(),
            'model' => $this->car->getModel(),
        ];
    }
}

Usage用法

$car = new Car();
$car->setType('type#');
$car->setModel('model#1');
$car->setColor(255);

$carDecorator = new CarArrayDecorator($car);
$carResponseData = $carDecorator->getArray();

So it will be more beautiful and more correct code.所以它会更漂亮,更正确的代码。

Since a lot of people find this question because of having trouble with dynamically access attributes of an object, I will just point out that you can do this in PHP: $valueRow->{"valueName"}由于很多人因为在动态访问对象的属性时遇到问题而发现这个问题,我将指出您可以在 PHP 中执行此操作: $valueRow->{"valueName"}

In context (removed HTML output for readability):在上下文中(为了可读性删除了 HTML 输出):

$valueRows = json_decode("{...}"); // Rows of unordered values decoded from a JSON object

foreach ($valueRows as $valueRow) {

    foreach ($references as $reference) {

        if (isset($valueRow->{$reference->valueName})) {
            $tableHtml .= $valueRow->{$reference->valueName};
        }
        else {
            $tableHtml .= " ";
        }
    }
}

By using typecasting you can resolve your problem.通过使用类型转换,您可以解决您的问题。 Just add the following lines to your return object:只需将以下行添加到您的返回对象中:

$arrObj = array(yourReturnedObject);

You can also add a new key and value pair to it by using:您还可以使用以下方法向其添加新的键值对:

$arrObj['key'] = value;

There's my proposal, if you have objects in objects with even private members:这是我的建议,如果您在对象中甚至有私有成员的对象:

public function dismount($object) {
    $reflectionClass = new \ReflectionClass(get_class($object));
    $array = array();
    foreach ($reflectionClass->getProperties() as $property) {
        $property->setAccessible(true);
        if (is_object($property->getValue($object))) {
            $array[$property->getName()] = $this->dismount($property->getValue($object));
        } else {
            $array[$property->getName()] = $property->getValue($object);
        }
        $property->setAccessible(false);
    }
    return $array;
}

I think it is a nice idea to use traits to store object-to-array converting logic.我认为使用特征来存储对象到数组的转换逻辑是个好主意。 A simple example:一个简单的例子:

trait ArrayAwareTrait
{
    /**
     * Return list of Entity's parameters
     * @return array
     */
    public function toArray()
    {
        $props = array_flip($this->getPropertiesList());
        return array_map(
            function ($item) {
                if ($item instanceof \DateTime) {
                    return $item->format(DATE_ATOM);
                }
                return $item;
            },
            array_filter(get_object_vars($this), function ($key) use ($props) {
                return array_key_exists($key, $props);
            }, ARRAY_FILTER_USE_KEY)
        );
    }


    /**
     * @return array
     */
    protected function getPropertiesList()
    {
        if (method_exists($this, '__sleep')) {
            return $this->__sleep();
        }
        if (defined('static::PROPERTIES')) {
            return static::PROPERTIES;
        }
        return [];
    }
}

class OrderResponse
{
    use ArrayAwareTrait;

    const PROP_ORDER_ID = 'orderId';
    const PROP_TITLE = 'title';
    const PROP_QUANTITY = 'quantity';
    const PROP_BUYER_USERNAME = 'buyerUsername';
    const PROP_COST_VALUE = 'costValue';
    const PROP_ADDRESS = 'address';

    private $orderId;
    private $title;
    private $quantity;
    private $buyerUsername;
    private $costValue;
    private $address;

    /**
     * @param $orderId
     * @param $title
     * @param $quantity
     * @param $buyerUsername
     * @param $costValue
     * @param $address
     */
    public function __construct(
        $orderId,
        $title,
        $quantity,
        $buyerUsername,
        $costValue,
        $address
    ) {
        $this->orderId = $orderId;
        $this->title = $title;
        $this->quantity = $quantity;
        $this->buyerUsername = $buyerUsername;
        $this->costValue = $costValue;
        $this->address = $address;
    }

    /**
     * @inheritDoc
     */
    public function __sleep()
    {
        return [
            static::PROP_ORDER_ID,
            static::PROP_TITLE,
            static::PROP_QUANTITY,
            static::PROP_BUYER_USERNAME,
            static::PROP_COST_VALUE,
            static::PROP_ADDRESS,
        ];
    }

    /**
     * @return mixed
     */
    public function getOrderId()
    {
        return $this->orderId;
    }

    /**
     * @return mixed
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @return mixed
     */
    public function getQuantity()
    {
        return $this->quantity;
    }

    /**
     * @return mixed
     */
    public function getBuyerUsername()
    {
        return $this->buyerUsername;
    }

    /**
     * @return mixed
     */
    public function getCostValue()
    {
        return $this->costValue;
    }

    /**
     * @return string
     */
    public function getAddress()
    {
        return $this->address;
    }
}

$orderResponse = new OrderResponse(...);
var_dump($orderResponse->toArray());

I use this (needed recursive solution with proper keys):我使用这个(需要带有适当键的递归解决方案):

    /**
     * This method returns the array corresponding to an object, including non public members.
     *
     * If the deep flag is true, is will operate recursively, otherwise (if false) just at the first level.
     *
     * @param object $obj
     * @param bool $deep = true
     * @return array
     * @throws \Exception
     */
    public static function objectToArray(object $obj, bool $deep = true)
    {
        $reflectionClass = new \ReflectionClass(get_class($obj));
        $array = [];
        foreach ($reflectionClass->getProperties() as $property) {
            $property->setAccessible(true);
            $val = $property->getValue($obj);
            if (true === $deep && is_object($val)) {
                $val = self::objectToArray($val);
            }
            $array[$property->getName()] = $val;
            $property->setAccessible(false);
        }
        return $array;
    }

Example of usage, the following code:用法示例,如下代码:

class AA{
    public $bb = null;
    protected $one = 11;

}

class BB{
    protected $two = 22;
}


$a = new AA();
$b = new BB();
$a->bb = $b;

var_dump($a)

Will print this:将打印这个:

array(2) {
  ["bb"] => array(1) {
    ["two"] => int(22)
  }
  ["one"] => int(11)
}

$Menu = new Admin_Model_DbTable_Menu(); 
$row = $Menu->fetchRow($Menu->select()->where('id = ?', $id));
$Addmenu = new Admin_Form_Addmenu(); 
$Addmenu->populate($row->toArray());

Here I've made an objectToArray() method, which also works with recursive objects, like when $objectA contains $objectB which points again to $objectA .在这里,我已经做了一个objectToArray()方法,该方法还与递归对象,如在$objectA中包含$objectB再次指向$objectA

Additionally I've restricted the output to public properties using ReflectionClass.此外,我使用 ReflectionClass 将输出限制为公共属性。 Get rid of it, if you don't need it.如果你不需要它,就摆脱它。

    /**
     * Converts given object to array, recursively.
     * Just outputs public properties.
     *
     * @param object|array $object
     * @return array|string
     */
    protected function objectToArray($object) {
        if (in_array($object, $this->usedObjects, TRUE)) {
            return '**recursive**';
        }
        if (is_array($object) || is_object($object)) {
            if (is_object($object)) {
                $this->usedObjects[] = $object;
            }
            $result = array();
            $reflectorClass = new \ReflectionClass(get_class($this));
            foreach ($object as $key => $value) {
                if ($reflectorClass->hasProperty($key) && $reflectorClass->getProperty($key)->isPublic()) {
                    $result[$key] = $this->objectToArray($value);
                }
            }
            return $result;
        }
        return $object;
    }

To identify already used objects, I am using a protected property in this (abstract) class, named $this->usedObjects .为了识别已使用的对象,我在这个(抽象)类中使用了一个受保护的属性,名为$this->usedObjects If a recursive nested object is found, it will be replaced by the string **recursive** .如果找到递归嵌套对象,它将被字符串**recursive**替换。 Otherwise it would fail in because of infinite loop.否则它会因为无限循环而失败。

Not a new solution but includes toArray method conversion when available 不是新的解决方案,但包括可用的toArray方法转换

function objectToArray($r)
{
  if (is_object($r)) {
    if (method_exists($r, 'toArray')) {
      return $r->toArray(); // returns result directly
    } else {
      $r = get_object_vars($r);
    }
  }

  if (is_array($r)) {
    $r = array_map(__FUNCTION__, $r); // recursive function call
  }

  return $r;
}

I tested it in Laravel Collections, this is working well.我在 Laravel Collections 测试过,效果很好。

function objectToArray($data)
{
    if (is_array($data) || is_object($data))
    {
        $result = [];
        foreach ($data as $key => $value)
        {
            $result[$key] = (is_array($data) || is_object($data)) ? objectToArray($value) : $value;
        }
        return $result;
    }
    return $data;
}

For the purpose of Unit Testig, I would recommend using json_decode(json_encode($object), true) instead.出于 Unit Testig 的目的,我建议使用json_decode(json_encode($object), true)代替。 Because if you try to use (array) $obj for a complex object such as the one below, unit testing will fail.因为如果您尝试将(array) $obj用于复杂对象,例如下面的对象,单元测试将失败。 Consider the following test case:考虑以下测试用例:

在此处输入图片说明

Hope this helps someone!希望这对某人有帮助!

有一种更简单的方法,每次都有效

$output = json_decode(json_encode($inputObject), true);

A short & clean way一个简短而干净的方式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM