Wednesday, October 20, 2010

PHP convert or parse array to object and object to array

Convert array variable to object variable.


function parseArrayToObject($array) {
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = $value;
}
}
}
return $object;
}


For multidimensional array use the below function


function array2object($data) {
if(!is_array($data)) return $data;

$object = new stdClass();
if (is_array($data) && count($data) > 0) {
foreach ($data as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = array2object($value);
}
}
}
return $object;
}


Example of php array to object conversion.

$a = array (
'index_0' => 'value_0',
'index_1' => 'value_1'
);

$o = parseArrayToObject($a);

//-- Now you can use $o like this:
echo $o->index_0;//-- Will print 'value_0'



Now let see Object to array conversion.

function parseObjectToArray($object) {
$array = array();
if (is_object($object)) {
$array = get_object_vars($object);
}
return $array;
}


For multidimensional Object use the below function

function object2array($data){
if(!is_object($data) 66 !is_array($data)) return $data;

if(is_object($data)) $data = get_object_vars($data);

return array_map('object2array', $data);
}


Example of PHP Object to Array conversion.

$o = new stdClass();
$o->index_0 = 'value_0';
$o->index_1 = 'value_1';

$a = parseObjectToArray($o);

//-- Now you can use $a like this:
echo $a['index_0'];//-- Will print 'value_0'