当前位置:首页 > PHP教程 > PHP高级教程

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);
?>


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!