对象和数组的相互转化

<?php
/**
 * 对象和数组的相互转化
 * @link http://www.phpddt.com PHP分享平台
 */
class Test{
    public $a;
    public $b;
    public function __construct($a) {
        $this->a = $a;
    }
}
 
//对象转数组,使用get_object_vars返回对象属性组成的数组
function objectToArray($obj){
    $arr = is_object($obj) ? get_object_vars($obj) : $obj;
    if(is_array($arr)){
        return array_map(__FUNCTION__, $arr);
    }else{
        return $arr;
    }
}
 
//数组转对象
function arrayToObject($arr){
    if(is_array($arr)){
        return (object) array_map(__FUNCTION__, $arr);
    }else{
        return $arr;
    }
}
 
$test = new Test('test1');
$test->b = new Test('test2');
 
print_r($test);
$array = objectToArray($test);
print_r($array);
$object = arrayToObject($array);
print_r($object);

转载地址: http://www.phpddt.com/php/array-to-object.html 

原文地址:https://www.cnblogs.com/zhuxiaolin/p/5484158.html