Php array and object conversion method functionarrayToObject ($ e) {if (gettype ($ e )! & Amp; 39; array & amp; 39;) return; foreach ($ eas $ k & gt; $ v) {if (gettype ($ v) & amp; 39
Php array and object conversion method
- Function arrayToObject ($ e ){
- If (gettype ($ e )! = 'Array') return;
- Foreach ($ e as $ k => $ v ){
- If (gettype ($ v) = 'array' | getType ($ v) = 'object ')
- $ E [$ k] = (object) arrayToObject ($ v );
- }
- Return (object) $ e;
- }
-
- Function objectToArray ($ e ){
- $ E = (array) $ e;
- Foreach ($ e as $ k => $ v ){
- If (gettype ($ v) = 'resource') return;
- If (gettype ($ v) = 'object' | gettype ($ v) = 'array ')
- $ E [$ k] = (array) objectToArray ($ v );
- }
- Return $ e;
- }
For how to convert arrays to objects, see some posts on phpx.
- $ Andy = array ();
- $ Andy ['A'] = 1;
- $ Andy ['B'] = 2;
- $ Andy ['c'] = 3;
To forcibly convert andy to an array, it seems that the reference is more convenient, mainly because it is->
- $ Andy = array ();
- $ Andy = (object) $ andy;
- $ Andy-> a = 1;
- $ Andy-> B = 2;
- $ Andy-> c = 3;
It is also troublesome, and StdClass is used again
- $ Andy = new StdClass;
- $ Andy-> a = 1;
- $ Andy-> B = 2;
- $ Andy-> c = 3;
StdClass is a base class of PHP. almost all classes inherit this class, so it can be new at any time. This variable can be made an object. at the same time, this base class has another special feature, that is, there is no method. here, there is also a problem with the consumption of objects and array resources: the uniqueness of the PHP5 object, the object is called anywhere, these parameters reference the address type, so the resources consumed are slightly less. when assigning values to the address type on other pages, they are directly modified instead of referencing a copy, the array should be the most convenient in the use of the program. However, every time the array is referenced ($ a = $ B), a copy is actually created, and after the array is unset, it still occupies the memory (not tested), and there is also a function arrayobject, which can directly convert the array into an object. this is also a good way.
- ArrayObject ::__ construct -- Construct a new array object
- $ Array = array ('1' => 'one ',
- '2' => 'two ',
- '3' => 'Three ');
- $ Arrayobject = new ArrayObject ($ array );
- Print_r ($ arrayobject );
- ?>
- ArrayObject Object
- (
- [1] => one
- [2] => two
- [3] => three
- )
After testing, the object can be converted to an array or forced conversion:
$ Arr = (array) $ obj;
The conversion result of the following example can be compared:
- Tag Object
- (
- [Name] => main
- [Text] =>
- [Parrent] =>
- [Content] =>
- [Props] => Array
- (
- )
-
- [Inner] => Array
- (
- )
-
- [Level] => 0
- )
-
- Array
- (
- [Name] => main
- [Text] =>
- [Parrent] =>
- [Content] =>
- [Props] => Array
- (
- )
-
- [Inner] => Array
- (
- )
-
- [Level] => 0
- )