Several Methods of Transforming stdClass Object to array in PHP
- 2021-06-28 08:58:16
- OfStack
Method 1:
//PHP stdClass Object turn 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:
$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 it is 10W's data volume, the execution needs 1s, the structure is more complex, can reach 3s, the performance is too bad
You can replace it with the following:
function object2array(&$object) {
$object = json_decode( json_encode( $object),true);
return $object;
}
However, json's features can only be targeted at utf8, otherwise they must be transcoded first.