Skip to content

Instantly share code, notes, and snippets.

@mingyun
Created June 29, 2014 14:40
Show Gist options
  • Save mingyun/0a527920ee6b07746bc4 to your computer and use it in GitHub Desktop.
Save mingyun/0a527920ee6b07746bc4 to your computer and use it in GitHub Desktop.
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;print_r($arr);
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment