Convert an array to an object with Stdclass
PHP code
The code is as follows |
Copy Code |
$arr = Array (); $arr [' a '] = 1; $arr [' b '] = 2; $arr [' c '] = 3; $arr = Array (); $arr [' a '] = 1; $arr [' b '] = 2; $arr [' c '] = 3; |
After converting with Stdclass:
PHP code
The code is as follows |
Copy Code |
$object = new StdClass; $object->a = 1; $object->b = 2; $object->c = 3; $object = new StdClass; $object->a = 1; $object->b = 2; $object->c = 3; |
Stdclass is a base class for PHP, and almost all classes inherit this class, so any time you can be new, you can make this variable an object. At the same time, this base class has a special place, there is no way
The place I'm applying is the simplexml_load_string () in SimpleXML, because all the objects are returned, and if the data is more cumbersome to extract, the following function is applied
The code is as follows |
Copy Code |
function Object_to_array ($obj) { $_arr = Is_object ($obj)? Get_object_vars ($obj): $obj; foreach ($_arr as $key => $val) { $val = (Is_array ($val) | | | is_object ($val))? Object_to_array ($val): $val; $arr [$key] = $val; } return $arr; }
|
Array into an object
The code is as follows |
Copy Code |
<?php $array = Array (1 => php, 2 => Java, 3 => C); $arrayobject = new Arrayobject ($array); Var_dump ($arrayobject); ?> |
Run Result:
The code is as follows |
Copy Code |
Object (Arrayobject) #1 (1) {[Storage]: "Arrayobject":p rivate]=> Array (3) {[1]=> string (3) "PHP" [2]=> string (4 ) "Java" [3]=> string (3) "C"}} |
A class: Arrayobject, you can directly convert an array to an object
PHP code
The code is as follows |
Copy Code |
$array = Array (' 1 ' => ' one ', ' 2 ' => ' two ', ' 3 ' => ' three '); $arrayobject = new Arrayobject ($array); Var_dump ($arrayobject); $array = Array (' 1 ' => ' one ', ' 2 ' => ' two ', ' 3 ' => ' three '); $arrayobject = new Arrayobject ($array); Var_dump ($arrayobject); |
Results:
The code is as follows |
Copy Code |
PHP code Object (Arrayobject) #1 (3) { [1]=> String (3) "One" [2]=> String (3) "Two" [3]=> String (5) "three" } |