Home  >  Article  >  Backend Development  >  How to convert object into array in php

How to convert object into array in php

PHPz
PHPzOriginal
2023-04-12 13:53:22768browse

In PHP development, two data types, Object and Array, are often used. They each have their own advantages and disadvantages, but in some scenarios they need to be converted to each other. In this article, we will introduce how to convert them to each other. Object is converted to Array.

In PHP, you can use forced type conversion to convert the Object type into the Array type. The specific implementation is as follows:

function objectToArray($obj){
    $arr = is_object($obj) ? get_object_vars($obj) : $obj;
    if(is_array($arr)){
        return array_map(__FUNCTION__, $arr);
    }else{
        return $arr;
    }
}

In the above code, first use the is_object() function to determine the incoming Whether the parameter is of type Object, if so, use the get_object_vars() function to obtain an array representation of the object's attributes and attribute values; if it is not of type Object, return it directly. Next, use the array_map() function to call the function recursively, convert each element of the multi-dimensional array into an array type, and finally return the converted array.

For example, we define a Person class:

class Person{
    public $name;
    public $age;
    function __construct($name, $age){
        $this->name = $name;
        $this->age = $age;
    }
}

Instantiate a Person object:

$person = new Person('Tom', 18);

Then use the above method to convert it into an array:

$array = objectToArray($person);
print_r($array);

The output results are as follows:

Array
(
    [name] => Tom
    [age] => 18
)

As can be seen from the above code, the Person object is converted into an array by using the objectToArray() function, and the attribute value of each attribute is successfully obtained. In this way, the array in this example can be used directly in some scenarios where arrays are used.

In daily development, it should be noted that there are some differences between arrays and objects. For example, arrays can use array-related functions and syntax, while objects can use class methods and properties. Therefore, during the conversion process, it is necessary to respond to the usage scenarios and master them flexibly.

The above is the detailed content of How to convert object into array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn