On Tue, Dec 2, 2008 at 7:48 PM, Micah Gersten <micah@xxxxxxxxxxx> wrote: > VamVan wrote: > > Hello All, > > > > I was stuck with this issue. So just felt the need to reach out to other > > strugglers. > > May be people might enjoy this: > > > > Here is the code for object to array and array to object conversion: > > > > function object_2_array($data) > > { > > if(is_array($data) || is_object($data)) > > { > > $result = array(); > > foreach ($data as $key => $value) > > { > > $result[$key] = object_2_array($value); > > } > > return $result; > > } > > return $data; > > } > > > > function array_2_object($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; > > } > > > > have fun !!!!! > > > > Thanks > > > > > ... > As for the object to array, the same thing applies: > http://us2.php.net/manual/en/language.types.array.php > > $array = (array) $object; not quite, take a look at VamVan's object_2_array(), its recursive. a simple type-cast will only alter the outermost layer of the $object in your example above. im not sure, but im assuming VamVan may have meant to make array_2_object() recursive as well ?? that would be more consistent anyway imo.. heres a simple script to illustrate the shallow nature of type-casting <?php $arr = array( 'b' => array( 'c' => array( 'd' ) ) ); $obj = new stdClass(); $obj->b = new stdClass(); $obj->b->c = new stdClass(); $obj->b->c->d = new stdClass(); var_dump((array)$obj); var_dump((object)$arr); ?> results in phdelnnobbe:~ nnobbe$ php arrayToObject.php array(1) { ["b"]=> object(stdClass)#2 (1) { ["c"]=> object(stdClass)#3 (1) { ["d"]=> object(stdClass)#4 (0) { } } } } object(stdClass)#5 (1) { ["b"]=> array(1) { ["c"]=> array(1) { [0]=> string(1) "d" } } } > Not sure if these are PHP 5 only or not. the manual should say. -nathan