Copy Code code as follows:
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;
}
The above is from Cnblogs Jaiho
PHP multi-layered array and object conversions
The use of multilayer arrays and object transformations is simple and facilitates the processing of multilayer arrays and objects in webservice.
Simple (array) and (object) can only handle single layer of data, and for multiple layers of array and object conversion is powerless.
With Json_decode ($object) You can convert an object to an array at once, but there are problems with non-ASCII characters that are not utf-8 encoded in object, such as GBK Chinese, not to mention Json_ The performance of encode and Decode is also doubtful.
The following code:
Copy Code code as follows:
<?php
function Objecttoarray ($d) {
if (Is_object ($d)) {
Gets the properties of the given object
With Get_object_vars function
$d = Get_object_vars ($d);
}
if (Is_array ($d)) {
/*
* Return array converted to object
* Using __function__ (Magic constant)
* For Recursive call
*/
Return Array_map (__function__, $d);
}
else {
Return array
return $d;
}
}
function Arraytoobject ($d) {
if (Is_array ($d)) {
/*
* Return array converted to object
* Using __function__ (Magic constant)
* For Recursive call
*/
Return (object) Array_map (__function__, $d);
}
else {
Return object
return $d;
}
}
Useage:
Create New StdClass Object
$init = new StdClass;
ADD some test data
$init->foo = "Test data";
$init->bar = new StdClass;
$init->bar->baaz = "testing";
$init->bar->fooz = new StdClass;
$init->bar->fooz->baz = "Testing Again";
$init->foox = "Just test";
Convert array to object and then object back to array
$array = Objecttoarray ($init);
$object = Arraytoobject ($array);
Print objects and Array
Print_r ($init);
echo "\ n";
Print_r ($array);
echo "\ n";
Print_r ($object);
?>