/**
* Conversion between PHP objects and arrays
*
* @author flyer0126
* @since 2012/05/03
**/
1. using (array) and (object), simple processing
$objTemp = (object) array ();
$objTemp->a = 1;
$objTemp->b = 2;
$objTemp->c = 3;
$arrTemp = (array) $objTemp;
Print_r ($objTemp);
Print_r ($arrTemp);
/**
StdClass Object
(
[A] = 1
[B] = 2
[C] = 3
)
Array
(
[A] = 1
[B] = 2
[C] = 3
)
**/
PS: Simple (array) and (object) can only handle single-layer data, for multi-layered array and object conversion is powerless.
2. Conversion processing between multidimensional arrays and objects
/**
* Convert an object to a multidimensional array
*
**/
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;
}
}
/**
* Convert multidimensional arrays to objects
*
**/
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:
$init = new StdClass;
$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);
Print_r ($array);
Print_r ($object);
/**
StdClass Object
(
[foo] = Test data
[Bar] = StdClass Object
(
[Baaz] = Testing
[Fooz] = StdClass Object
(
[Baz] = testing again
)
)
[Foox] = Just test
)
Array
(
[foo] = Test data
[Bar] = = Array
(
[Baaz] = Testing
[Fooz] = = Array
(
[Baz] = testing again
)
)
[Foox] = Just test
)
StdClass Object
(
[foo] = Test data
[Bar] = StdClass Object
(
[Baaz] = Testing
[Fooz] = StdClass Object
(
[Baz] = testing again
)
)
[Foox] = Just test
)
**/