Home Backend Development PHP Problem Convert object to array in php

Convert object to array in php

May 05, 2023 pm 10:40 PM

In PHP, an object is a complex data type that can contain multiple properties and methods. Sometimes we need to convert objects into arrays for operations, such as storing objects in a database or converting objects into JSON format. This article will explain how to convert objects to arrays in PHP.

Method 1: Use forced type conversion

You can use forced type conversion in PHP to convert an object into an array. The specific method is to use the properties of the object as the keys in the array, the value of the property as the value of the array, and then return the array.

The following is a sample code that implements the function of converting a Person object into an array:

class Person {
    public $name;
    public $age;
    public $gender;

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

$person = new Person('John', 28, 'male');

// 使用强制类型转换将对象转换为数组
$array = (array) $person;
print_r($array); // 输出结果为:Array ( [name] => John [age] => 28 [gender] => male )
Copy after login

As you can see, in the above example, we used forced type conversion to convert Person Object converted to array. Casting is very convenient, but it has a disadvantage, that is, it can only convert the public properties of the object into an array, but cannot convert private or protected properties into an array.

Method 2: Use the get_object_vars function

In addition to forced type conversion, PHP also provides another method to convert an object into an array. This method is to use the get_object_vars function. This function accepts an object as a parameter and converts all properties of the object into an array and returns it.

The following is a sample code that implements the function of converting a Person object into an array:

class Person {
    public $name;
    public $age;
    public $gender;

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

$person = new Person('John', 28, 'male');

// 使用get_object_vars函数将对象转换为数组
$array = get_object_vars($person);
print_r($array); // 输出结果为:Array ( [name] => John [age] => 28 [gender] => male )
Copy after login

Unlike forced type conversion, the get_object_vars function can convert all attributes of the object into an array, Includes private properties and protected properties.

Method 3: Use json_decode and json_encode functions

In addition to the above two methods, we can also convert the object to JSON format first, and then convert the JSON format into an array. This method requires the use of json_decode and json_encode functions.

The following is a sample code that implements the function of converting a Person object into an array:

class Person {
    public $name;
    public $age;
    public $gender;

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

$person = new Person('John', 28, 'male');

// 将对象转换为JSON格式
$json = json_encode($person);

// 将JSON格式转换为数组
$array = json_decode($json, true);
print_r($array); // 输出结果为:Array ( [name] => John [age] => 28 [gender] => male )
Copy after login

By using the json_decode and json_encode functions, we can simply convert the object into an array.

Summary:

In PHP, there are many ways to convert objects into arrays. We can use methods such as cast, get_object_vars function, json_decode and json_encode functions. Different methods have different applicable scenarios, and we can choose the appropriate method according to actual needs. When using forced type conversion, you need to note that only public attributes can be converted into arrays; when using the get_object_vars function, you can convert all attributes into arrays; when using the json_decode and json_encode functions, you need to pay attention to the JSON format conversion.

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

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

How do you retrieve data from a database using PHP? How do you retrieve data from a database using PHP? Mar 20, 2025 pm 04:57 PM

Article discusses retrieving data from databases using PHP, covering steps, security measures, optimization techniques, and common errors with solutions.Character count: 159

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

What is the purpose of mysqli_query() and mysqli_fetch_assoc()? What is the purpose of mysqli_query() and mysqli_fetch_assoc()? Mar 20, 2025 pm 04:55 PM

The article discusses the mysqli_query() and mysqli_fetch_assoc() functions in PHP for MySQL database interactions. It explains their roles, differences, and provides a practical example of their use. The main argument focuses on the benefits of usin

See all articles