php怎么把对象转为数组
1个回答
展开全部
这里定义2个php匿名对象和数组相互转换的函数,代码如下:
function array2object($array) {
if (is_array($array)) { $obj = new StdClass(); foreach ($array as $key => $val){ $obj->$key = $val; } } else { $obj = $array; } return $obj;}function object2array($object) { if (is_object($object)) { foreach ($object as $key => $value) { $array[$key] = $value; } } else { $array = $object; } return $array;}
用法示例如下:
$array = array('foo' => 'bar','one' => 'two','three' => 'four');$obj = array2object($array);print $obj->one; // output's "two"$arr = object2array($obj);print $arr['foo']; // output's bar
function array2object($array) {
if (is_array($array)) { $obj = new StdClass(); foreach ($array as $key => $val){ $obj->$key = $val; } } else { $obj = $array; } return $obj;}function object2array($object) { if (is_object($object)) { foreach ($object as $key => $value) { $array[$key] = $value; } } else { $array = $object; } return $array;}
用法示例如下:
$array = array('foo' => 'bar','one' => 'two','three' => 'four');$obj = array2object($array);print $obj->one; // output's "two"$arr = object2array($obj);print $arr['foo']; // output's bar
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |