Home  >  Article  >  Backend Development  >  How to convert object to array in php

How to convert object to array in php

王林
王林Original
2020-07-10 14:20:4011282browse

The way PHP converts an object into an array is: you can first judge it through the is_object() function, and then perform forced type conversion. The is_object() function is used to detect whether a variable is an object. Specific conversion method: [$arr = (array)($object)].

How to convert object to array in php

#If you want to convert the object into an array, you can first judge it through the is_object() function, and then perform forced type conversion.

(Recommended tutorial: php tutorial)

Function introduction:

is_object() function is used to detect whether a variable is an object.

Function syntax:

bool is_object ( mixed $var )

Parameter description:

  • $var: variable to be detected.

Return value:

If the specified variable is an object, TRUE is returned, otherwise FALSE is returned.

Code implementation:

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

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