The array is the soul of PHP, very powerful, but sometimes object-oriented programming is also very convenient, the array and the switch between the object is often the case:
Example One
| The code is as follows |
Copy Code |
| /** * Array to Object * * Array $arr @param array * @return Object */ function Array_to_object ($arr) { if (GetType ($arr)!= ' array ') { Return } foreach ($arr as $k => $v) { if (GetType ($v) = = ' Array ' | | GetType ($v) = = ' object ') { $arr [$k] = (object) array_to_object ($v); } } Return (object) $arr; } /** * Object to Array * * @param object $obj objects * @return Array */ function Object_to_array ($obj) { $obj = (array) $obj; foreach ($obj as $k => $v) { if (GetType ($v) = = ' Resource ') { Return } if (GetType ($v) = = ' object ' | | GetType ($v) = = ' array ') { $obj [$k] = (array) object_to_array ($v); } } return $obj; } |
Example 2
| The code is as follows |
Copy Code |
| <?php Class test{ public $a; Public $b; Public function __construct ($a) { $this->a = $a; } }
object to array, using Get_object_vars to return an array of object properties function Objecttoarray ($obj) { $arr = Is_object ($obj)? Get_object_vars ($obj): $obj; if (Is_array ($arr)) { Return Array_map (__function__, $arr); }else{ return $arr; } }
Array to Object function Arraytoobject ($arr) { if (Is_array ($arr)) { Return (object) Array_map (__function__, $arr); }else{ return $arr; } }
$test = new Test (' test1 '); $test->b = new Test (' test2 ');
Print_r ($test); $array = Objecttoarray ($test); Print_r ($array); $object = Arraytoobject ($array); Print_r ($object); |