Home >Backend Development >PHP Problem >How to convert obj to array in php

How to convert obj to array in php

PHPz
PHPzOriginal
2023-04-26 09:06:281181browse

In PHP development, we often need to convert objects (Object) to arrays (Array), especially when using the ORM (Object Relational Mapping) framework. This article will introduce several methods to convert PHP objects into arrays.

Method 1: Use the object to array function

PHP provides a function that converts objects into arraysget_object_vars(), which converts the properties of the object into arrays key-value pairs, returns an array of key-value pairs. An example of using this function is as follows:

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

$user = new User('Lucy', 20);
$arrayUser = get_object_vars($user);
print_r($arrayUser);

In this example, we define a class named User, which contains two public properties $name and $age, and initialize these two properties in the constructor . Then a $user object is instantiated and passed into the get_object_vars() function, which will return an array $arrayUser consisting of attribute names and attribute values.

Method 2: Custom object to array method

In some cases, we may need to customize the way in which objects are converted to arrays. For example, we don't want to convert all properties to arrays, but only some properties or represent properties with different key names. At this time, we can define a "toArray()" method in the object and freely define the conversion method. An example of using this method is as follows:

class Student {
    private $name;
    private $age;
    private $gender;
    public function __construct($name, $age, $gender)
    {
        $this->name = $name;
        $this->age = $age;
        $this->gender = $gender;
    }
    public function toArray() {
        return [
            '姓名' => $this->name,
            '年龄' => $this->age,
            '性别' => $this->gender
        ];
    }
}

$stu = new Student('Bob', 23, '男');
$arrayStu = $stu->toArray();
print_r($arrayStu);

In this example, we define a class named Student, which contains three private properties $name, $age and $gender, and initialize these in the constructor. three attributes. In the class, a public method named "toArray()" is defined, which returns an array consisting of attribute names and attribute values, and is converted into an array $arrayStu with Chinese key names.

Method 3: Use the features of the json_decode function

In PHP, there are some functions that can convert JSON format strings into arrays. Among these functions, the json_decode() function is the most commonly used. Just imagine, if we can convert the object into a string in JSON format, and then use the json_decode() function to convert it into an array, wouldn't we also be able to convert the object into an array? An example is as follows:

class Car {
    public $brand;
    public $color;
    public $price;
    public function __construct($brand, $color, $price)
    {
        $this->brand = $brand;
        $this->color = $color;
        $this->price = $price;
    }
}

$car = new Car('Benz', 'black', 400000);
$jsonCar = json_encode($car);
$arrayCar = json_decode($jsonCar, true);
print_r($arrayCar);

In this example, we define a class named Car, which contains three public properties $brand, $color and $price, and initialize these three properties in the constructor. Then a $car object is instantiated, converted into a JSON format string using the json_encode() function, and then converted into an array using the json_decode() function. Finally, we get the array $arrayCar consisting of attribute names and attribute values. It should be noted that the object must be a public property when using this method, otherwise it will not be converted.

Summary:

In PHP, there are many ways to convert objects into arrays. We can choose the appropriate method according to the actual situation. Of course, the above example only shows part of it, and more conversion methods are waiting for us to discover and implement. I hope that through this article, readers can master the method of converting objects into arrays in PHP, and also deepen their understanding and application of PHP.

The above is the detailed content of How to convert obj to 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