This article introduces how to convert an array to an object in php or convert an object to an array object. If you need it, you can refer to this example in this article. This article introduces how to convert an array to an object in php or convert an object to an array object. If you need it, you can refer to this example in this article.
Script ec (2); script
Use stdClass to convert an array to an object
Php code
The Code is as follows: |
|
$ Arr = array (); $ Arr ['a'] = 1; $ Arr ['B'] = 2; $ Arr ['C'] = 3; $ Arr = array (); $ Arr ['a'] = 1; $ Arr ['B'] = 2; $ Arr ['C'] = 3; |
After stdClass conversion:
Php code
The Code is as follows: |
|
$ 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 of PHP. Almost all classes inherit this class, so it can be new at any time and make this variable an object. At the same time, this base class has another special point, that is, there is no method
My application is on simplexml_load_string () in simplexml, because all objects are returned. If it is difficult to extract data, the following function is applied.
The Code is as follows: |
|
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; }
|
Convert an array to an object
The Code is as follows: |
|
$ Array = array (1 => php, 2 => java, 3 => c ); $ Arrayobject = new ArrayObject ($ array ); Var_dump ($ arrayobject ); ?> |
Running result:
The Code is as follows: |
|
Object (ArrayObject) #1 (1) {["storage": "ArrayObject": private] => array (3) {[1] => string (3) "php" [2] => string (4) "java" [3] => string (3) "c "}} |
A class: ArrayObject, which can directly convert an array into an object
Php code
The Code is as follows: |
|
$ 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 ); |
Result:
The Code is as follows: |
|
Php code Object (ArrayObject) #1 (3 ){ [1] => String (3) "one" [2] => String (3) "two" [3] => String (5) "three" } |