The example of this article describes the method of using recursive implementations of PHP arrays and objects. Share to everyone for your reference. The implementation methods are as follows:
Here are some simple questions about the conversion of objects to arrays, using recursion to write two methods as follows:
?
1
2
3
4
5
6
7
8function 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;
}
?
1
2
3
4
5
6
7
8
9function 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;
}
?
1
2
3
4
5
6
7
8function Object_to_array ($e) {
$_arr = Is_object ($e)? Get_object_vars ($e): $e;
foreach ($_arr as $key => $val) {
$val = (Is_array ($val) | | | is_object ($val))? Object_to_array ($val): $val;
$arr [$key] = $val;
}
return $arr;
}
I hope this article will help you with your PHP program design.