PHP 将object转换为array

代码
<?php
/*** a complex object ***/
$obj = new stdClass;
$obj->foo = new stdClass;
$obj->foo->baz = 'baz';
$obj->bar = 'bar';

/**
*
* Convert an object to an array
*
* @param object $object The object to convert
* @reeturn array
*
*/
function objectToArray( $object )
{
if( !is_object( $object ) && !is_array( $object ) )
{
return $object;
}
if( is_object( $object ) )
{
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}

/*** convert the array to object ***/
$array = objectToArray( $obj );

/*** show the array ***/
print_r( $array );
?>

Array
(
[foo]
=> Array
(
[baz]
=> baz
)

[bar]
=> bar
)

 

posted @ 2010-04-21 10:59  DavidHHuan  阅读(833)  评论(0编辑  收藏  举报