Home > Article > Backend Development > How to convert object to array in php
Two methods: 1. Use json_encode to convert the object into json data, and then use json_decode to convert the json data into an array. The syntax is "json_decode(json_encode(object),TRUE)"; 2. Use get_object_vars() Function that returns an associative array of object properties, syntax "get_object_vars (object)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php converts objects Two methods for arrays
Method 1: Use the get_object_vars() function
get_object_vars() returns an associative array composed of object attributes.
Syntax:
get_object_vars ($obj)
Returns an associative array composed of properties defined in the object specified by obj.
Example:
<?php class gfg { private $geeks = 0.02; public $for = 1; public $Geeks = "php"; private $GEEKS; static $e; public function example() { var_dump(get_object_vars($this)); } } $example = new gfg; var_dump(get_object_vars($example)); $example->example(); ?>
Method 2: Use json_encode() and json_decode() functions
Use json_encode The function converts the object into json data, and then uses the json_decode function to convert the json data into an array.
<?php class gfg { public $geeks = 0.02; public $for = 1; public $Geeks = "php"; public $GEEKS; public $e; } $example = new gfg; var_dump(json_decode(json_encode($example),TRUE)); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert object to array in php. For more information, please follow other related articles on the PHP Chinese website!