您好,欢迎访问一九零五行业门户网

火炬之光有多少层 php简单对象与数组的转换函数代码php多层数组和对象的转换

复制代码 代码如下:
function arraytoobject($e){
if( gettype($e)!='array' ) return;
foreach($e as $k=>$v){
if( gettype($v)=='array' || gettype($v)=='object' )
$e[$k]=(object)arraytoobject($v);
}
return (object)$e;
}
function objecttoarray($e){
$e=(array)$e;
foreach($e as $k=>$v){
if( gettype($v)=='resource' ) return;
if( gettype($v)=='object' || gettype($v)=='array' )
$e[$k]=(array)objecttoarray($v);
}
return $e;
}
上面的内容来自 cnblogs jaiho
php多层数组和对象的转换
多层数组和对象转化的用途很简单,便于处理webservice中多层数组和对象的转化
简单的(array)和(object)只能处理单层的数据,对于多层的数组和对象转换则无能为力。
通过json_decode(json_encode($object)可以将对象一次性转换为数组,但是object中遇到非utf-8编码的非ascii字符则会出现问题,比如gbk的中文,何况json_encode和decode的性能也值得疑虑。
下面上代码:
复制代码 代码如下:
foo = test data;
$init->bar = new stdclass;
$init->bar->baaz = testing;
$init->bar->fooz = new stdclass;
$init->bar->fooz->baz = testing again;
$init->foox = just test;
// convert array to object and then object back to array
$array = objecttoarray($init);
$object = arraytoobject($array);
// print objects and array
print_r($init);
echo \n;
print_r($array);
echo \n;
print_r($object);
?>
以上就介绍了火炬之光有多少层 php简单对象与数组的转换函数代码php多层数组和对象的转换,包括了火炬之光有多少层方面的内容,希望对php教程有兴趣的朋友有所帮助。
其它类似信息

推荐信息