php多层数组与对象的转换实例代码

yipeiwu_com6年前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;
 // Add some test data
 $init->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 数据库 常见问题小结第1/3页

如果只有一种 方式使用数据库是正确的…… 您可以用很多的方式创建数据库设计、数据库访问和基于数据库的 PHP 业务逻辑代码,但最终一般以错误告终。本文说明了数据库设计和访问数据库的 PH...

PHP的时间戳与具体时间转化的简单实现

三个内置函数: time() //获取UNIX系统时间戳 mktime(hour,minute,second,month,day,year) //将指定时间转化为时间戳 d...

PHP中防止直接访问或查看或下载config.php文件的方法

或是,PHP的设计本身就避免直接查看文件内容的情况? 从安全角度考虑,这个系统级的文件应该做什么保护措施? 网友完善的答案 经调研,得出以下常用方法: 1 在程序中定义一个标识变量 复制...

浅谈php安全性需要注意的几点事项

在放假之初,我抽时间看了《白帽子讲web安全》,吴翰清基本上把web安全中所有能够遇到的问题、解决思路归纳总结得很清晰,也是我这一次整体代码安全性的基石。 我希望能分如下几个方面来分享自...

PHP合并两个或多个数组的方法

PHP合并两个或多个数组的方法

使用运算符“+” PHP的数组运算符“+”可以用来联合两个(或多个数组)。 <?php header("content-type:text/html;charset=...