Php Tutorial how to convert arrays and objects
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;
}
Some posts on converting arrays to objects are discussed in 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.
Make this variable an object. At the same time, this base class has another special point, that is, there is no method. Here
Another point is the resource consumption of objects and arrays: the uniqueness of PHP5 objects. Objects can be called anywhere.
It refers to the address type, so the resource consumption is a little less. When assigning values to other pages, it is directly modified instead
Is to reference a copy. Array should be the most convenient in the use of the program, but each time the array is referenced ($ a = $ B)
In fact, a copy is created, and the array is still occupied by memory after it is unset (not tested ). And
An arrayobject function can directly convert arrays into objects. This is also a good method.
ArrayObject ::__ construct -- Construct a new array object
<? Php
$ 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 tutorial] => Array
(
)
[Inner] => Array
(
)
[Level] => 0
)
Array
(
[Name] => main
[Text] =>
[Parrent] =>
[Content] =>
[Props] => Array
(
)
[Inner] => Array
(
)
[Level] => 0
)