How to convert php stdclass to array

藏色散人
Release: 2023-03-05 21:10:01
Original
4215 people have browsed it

php stdclass to array method: 1. Use the "object_array" method to convert stdClass Object to array; 2. Convert through the "json_decode" function; 3. Use the "object2array_pre" method to convert.

How to convert php stdclass to array

Recommended: "PHP Video Tutorial"

How to convert stdClass Object to array in PHP Method

PHP and JS usually use json to communicate, but the array passed by json is not a standard array, but a stdClass type. Then we can refer to the following methods for conversion.

Method one:

//PHP stdClass Object转array  
function object_array($array) {  
    if(is_object($array)) {  
        $array = (array)$array;  
     } if(is_array($array)) {  
         foreach($array as $key=>$value) {  
             $array[$key] = object_array($value);  
             }  
     }  
     return $array;  
}
Copy after login

Method two:

$array = json_decode(json_encode(simplexml_load_string($xmlString)),TRUE);
Copy after login

Method three:

function object2array_pre(&$object) {
        if (is_object($object)) {
            $arr = (array)($object);
        } else {
            $arr = &$object;
        }
        if (is_array($arr)) {
            foreach($arr as $varName => $varValue){
                $arr[$varName] = $this->object2array($varValue);
            }
        }
        return $arr;
    }
Copy after login

If the data volume is 10W, the execution will take 1s, structure If it is more complicated, it can reach 3s. The performance is too poor.

can be replaced with the following:

function object2array(&$object) {
             $object =  json_decode( json_encode( $object),true);
             return  $object;
    }
Copy after login

But for the characteristics of json, it can only be for utf8, otherwise it must be transcoded first.

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

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template