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

How to convert object to array in php

青灯夜游
青灯夜游Original
2022-05-26 19:30:228585browse

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)".

How to convert object to array in php

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();
  
?>

How to convert object to array in php

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));

?>

How to convert object to array in php

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!

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