Several methods to convert stdClass Object to array in PHP

高洛峰
Release: 2016-10-20 14:42:18
Original
1030 people have browsed it

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;  
}
Copy after login


Method 2:

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


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;
    }
Copy after login


If the amount of data is 10W, the execution will take 1 second. If the structure is more complex, it can reach 3 seconds. The performance is too bad
You can replace it 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.


Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!