php的数组和stdClass互相转化

将一个stdClass对象转化为数组
php的stdClass相当于一个Object

function object_to_array($obj) 
{ 
    $_arr = is_object($obj) ? get_object_vars($obj) : $obj; 
    foreach ($_arr as $key => $val) 
    { 
        $val = (is_array($val) || is_object($val)) ?       object_to_array($val) : $val; 
        $arr[$key] = $val; 
    } 
    return $arr; 
}

将一个数组转化为stdClass

function array_to_object($arr){
 
	$object = new stdClass;
	foreach($arr as $key=>$value){
		$object->$key = $value;
		}
	return $object;
	}

测试下

echo "\r\n";
$arr = array();                                            
$arr['a'] = 10;                                               
$arr['b'] = 22;                                               
$arr['c'] = 23;  
$arr['d'] = 26;
 
$sd = array_to_object($arr);
 
print_r($sd);
 
$arr = object_to_array($sd);
 
print_r($arr);


This entry was posted in PHP and tagged , , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/php-stdclass-array-exchange/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.
2020.03.24 评论已经全局关闭,有事加QQ聊天