Home >Backend Development >PHP Problem >How to convert an object to an array in PHP

How to convert an object to an array in PHP

PHPz
PHPzOriginal
2023-04-12 15:36:51788browse

In PHP, converting an object to an array is a frequent operation, because an array is a data structure that is more convenient for storing and processing data. This article will introduce how to convert an object into an array in PHP.

The method of converting an object to an array in PHP is very simple and can be achieved by casting the object to an array. You can use the (array) or json_decode() function:

Use the (array) function to convert the object into an array:

$obj = new stdClass();
$obj->name = "John";
$obj->age = 30;

$arr = (array)$obj;
print_r($arr);

This will output:

Array
(
    [name] => John
    [age] => 30
)

Please note that this will return an associative array whose keys are the object's property names and whose values ​​are the values ​​of the corresponding properties. If the object has protected or private properties, they are not accessible and will not be converted to an array. Additionally, if the object has methods, they are not included.

Use the json_decode() function to convert an object into an array

If you do not want to use forced type conversion, you can use the json_decode() function to convert an object to an array Decoded into an array. You can encode it to JSON format by calling json_encode() on an object, and then use json_decode() to convert it to an array.

$obj = new stdClass();
$obj->name = "John";
$obj->age = 30;

$json_obj = json_encode($obj);
$arr = json_decode($json_obj, true);

print_r($arr);

This will be converted to an associative array containing the property name and value:

Array
(
    [name] => John
    [age] => 30
)

It should be noted that casting the object to an array is different from using the json_decode() function The main difference between converting an object to an array is that casting is fast and simpler, while JSON parsing requires more system resources. Therefore, if you know that the object you want to convert is a simple object, a direct cast is faster and more convenient; whereas if you need to convert a more irregular and complex object into an array, using JSON parsing may be more appropriate.

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