Home  >  Article  >  Backend Development  >  Several methods to convert stdClass Object to array in PHP

Several methods to convert stdClass Object to array in PHP

WBOY
WBOYOriginal
2016-07-29 09:03:041184browse

Json is usually used for communication between PHP and JS, but the array passed by json is not a standard array, but of stdClass type. Then we can refer to the following methods for conversion.

Method 1:

//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;  
}

Method 2:

Copy the code The code is as follows:

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

Method 3:

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

If the data volume is 10W, the execution needs to be 1s , if the structure is more complex, it can reach 3s. The performance is too poor. You can replace it with the following:
function object2array(&$object) {
             $object =  json_decode( json_encode( $object),true);
             return  $object;
    }

But for the characteristics of json, it can only be for utf8, otherwise it must be transcoded first.
The above introduces several methods of converting stdClass Object to array in PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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