PHP 数组和对象的相互转化

对象和数组的相互转化在开发中也是很常见,一般不是多维的情况下直接(array)和(object)就可搞定了,多维的话,遍历下也就可以了:

 1 <?php
 2     class test
 3     {
 4         public $a,$b;
 5 
 6         public function __construct($a)
 7         {
 8             $this->a = $a;
 9         }
10     }
11     $t = new test(30);
12     //对象转数组
13     function object2array($obj)
14     {
15         $arr = is_object($obj) ? get_object_vars($obj) : $obj;
16 
17         if(is_array($arr))
18         {
19             return array_map(__FUNCTION__, $arr);
20         }
21         else
22         {
23             return $arr;
24         }
25     }
26     /*$xml = simplexml_load_file('simplexml.xml');    //对象
27     $arr = object2array($xml);    //将对象转为数组
28     $arr = $arr['post'];
29     foreach($arr as $v)
30     {
31         echo $v['title'];
32     }*/
33 
34     //数组转对象
35     function array2object($arr)
36     {
37         if(is_array($arr))
38         {
39             return (object) array_map(__FUNCTION__, $arr);
40         }
41         else
42         {
43             return $arr;
44         }
45     }
46 
47     $test = new Test('test1');
48     $test->b = new Test('test2');
49     $array = object2array($test);
50     print_r($array);
51     $object = array2object($array);
52     print_r($object);
53 ?>
原文地址:https://www.cnblogs.com/cloak/p/4991711.html