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

PHP function realizes mutual conversion between objects and arrays

伊谢尔伦
Release: 2016-11-26 14:19:15
Original
1005 people have browsed it

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

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


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