Home  >  Article  >  Backend Development  >  PHP function realizes mutual conversion between objects and arrays

PHP function realizes mutual conversion between objects and arrays

伊谢尔伦
伊谢尔伦Original
2016-11-26 14:19:15969browse

Convert array to object (recursively if it is a multi-dimensional array):

function arrayToObject($e){
    if( gettype($e)!='array' ) return;
    foreach($e as $k=>$v){
        if( gettype($v)=='array' || getType($v)=='object' )
            $e[$k]=(object)arrayToObject($v);
    }
    return (object)$e;
}

Convert object to array (use recursion to implement deep cloning):

function objectToArray($e){
    $e=(array)$e;
    foreach($e as $k=>$v){
        if( gettype($v)=='resource' ) return;
        if( gettype($v)=='object' || gettype($v)=='array' )
           $e[$k]=(array)objectToArray($v);
    }
    return $e;
}


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