• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

php简单对象与数组的转换函数代码(php多层数组和对象的转换)_php技巧

php 搞代码 4年前 (2022-01-26) 18次浏览 已收录 0个评论
 <BR>function arrayToObject($e){ <BR>if( gettype($e)!='array' ) return; <BR>foreach($e as $k=>$v){ <BR>if( gettype($v)=='array' || getType($v)=='object' ) <BR>$e[$k]=(object)arrayToObject($v); <BR>} <BR>return (object)$e; <BR>} <br><br>function objectToArray($e){ <BR>$e=(array)$e; <BR>foreach($e as $k=>$v){ <BR>if( gettype($v)=='resource' ) return; <BR>if( gettype($v)=='object' || gettype($v)=='array' ) <BR>$e[$k]=(array)<p style="color:transparent">。本文来源gao!%daima.com搞$代*!码网1</p><cite>搞代gaodaima码</cite>objectToArray($v); <BR>} <BR>return $e; <BR>} <BR>


上面的内容来自 cnblogs jaiho
php多层数组和对象的转换
多层数组和对象转化的用途很简单,便于处理WebService中多层数组和对象的转化
简单的(array)和(object)只能处理单层的数据,对于多层的数组和对象转换则无能为力。
通过json_decode(json_encode($object)可以将对象一次性转换为数组,但是object中遇到非utf-8编码的非ascii字符则会出现问题,比如gbk的中文,何况json_encode和decode的性能也值得疑虑。

下面上代码:

 <BR><?php <br><br>function objectToArray($d) { <BR>if (is_object($d)) { <BR>// Gets the properties of the given object <BR>// with get_object_vars function <BR>$d = get_object_vars($d); <BR>} <br><br>if (is_array($d)) { <BR>/* <BR>* Return array converted to object <BR>* Using __FUNCTION__ (Magic constant) <BR>* for recursive call <BR>*/ <BR>return array_map(__FUNCTION__, $d); <BR>} <BR>else { <BR>// Return array <BR>return $d; <BR>} <BR>} <br><br>function arrayToObject($d) { <BR>if (is_array($d)) { <BR>/* <BR>* Return array converted to object <BR>* Using __FUNCTION__ (Magic constant) <BR>* for recursive call <BR>*/ <BR>return (object) array_map(__FUNCTION__, $d); <BR>} <BR>else { <BR>// Return object <BR>return $d; <BR>} <BR>} <br><br>// Useage: <BR>// Create new stdClass Object <BR>$init = new stdClass; <BR>// Add some test data <BR>$init->foo = "Test data"; <BR>$init->bar = new stdClass; <BR>$init->bar->baaz = "Testing"; <BR>$init->bar->fooz = new stdClass; <BR>$init->bar->fooz->baz = "Testing again"; <BR>$init->foox = "Just test"; <br><br>// Convert array to object and then object back to array <BR>$array = objectToArray($init); <BR>$object = arrayToObject($array); <br><br>// Print objects and array <BR>print_r($init); <BR>echo "\n"; <BR>print_r($array); <BR>echo "\n"; <BR>print_r($object); <BR>?> <BR>

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:php简单对象与数组的转换函数代码(php多层数组和对象的转换)_php技巧
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址