php数组对象之间的转换
方法一:自定义函数
/**
* [object_to_array 对象转换为数组]
* @author cat_crazy 2017-01-03
* @param [object] $object [description]
* @return [array] [description]
*/
function object_to_array($object)
{
if(is_object($object)){
$arr = [];
foreach($object as $k => $val){
$arr[$k] = $val;
}
}else{
return false;
}
return $arr;
}
/**
* [array_to_object 数组转换为对象]
* @author cat_crazy 2017-01-03
* @param [array] $arr [description]
* @return [object] [description]
*/
function array_to_object($arr)
{
if(is_array($arr)){
$object = new stdClass();
foreach($arr as $k => $val){
$object->$k = $val;
}
}else{
return false;
}
return $object;
}
echo '<pre>';
$arr = ['name'=>'小花猫', 'age'=>'2', 'sex'=>'男'];
$object = array_to_object($arr);
var_dump($object);
$arr = object_to_array($object);
var_dump($arr);
方法二:强制类型转换
$arr = ['name'=>'小花猫', 'age'=>'2', 'sex'=>'男'];
$object = (object)$arr;
var_dump($object);
$arr = (array)$object;
var_dump($arr);