本篇文章为大家展示了使用php怎么将多层数组转换为对象,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
多层数组和对象转化的用途很简单,便于处理WebService中多层数组和对象的转化
简单的(array)和(object)只能处理单层的数据,对于多层的数组和对象转换则无能为力。
通过json_decode(json_encode($object)可以将对象一次性转换为数组,但是object中遇到非utf-8编码的非ascii字符则会出现问题,比如gbk的中文,何况json_encode和decode的性能也值得疑虑。
下面上代码:
代码如下:
<?php
function objectToArray($d) {
if (is_object($d)) {
//Gets the properties of the given object
//with get_object_vars function
$d=get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
}
else {
//Return array
return $d;
}
}
function arrayToObject($d) {
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return (object) array_map(__FUNCTION__, $d);
}
else {
//Return object
return $d;
}
}
//Useage:
//Create new stdClass Object
init=new stdClass美元;
,
//添加一些测试数据,初始化→美元foo=安馐詃ata"
, init→美元酒吧=new stdClass;
, init→美元栏→巴兹=癟esting"
, init→美元栏→fooz=new stdClass;
, init→美元栏→fooz→巴兹=安馐詀gain"
, init→美元foox=爸皇莟est"
,//数组转换为对象,然后对象返回数组
,数组=objectToArray美元($ init);
, $对象=arrayToObject(数组)美元;
,//打印对象和数组
, print_r ($ init);
,呼应“\ n"
, print_r(数组)美元;
,呼应“\ n"
, print_r(对象)美元;
?在
上述内容就是使用php怎么将多层数组转换为对象,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注行业资讯频道。