Adding array to an object breaks the array
Posted
by DisgruntledGoat
on Stack Overflow
See other posts from Stack Overflow
or by DisgruntledGoat
Published on 2010-05-14T15:18:40Z
Indexed on
2010/05/14
15:34 UTC
Read the original article
Hit count: 236
I have an array like this (output from print_r
):
Array
(
[price] => 700.00
[room_prices] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
)
[bills] => Array
(
[0] => Gas
)
)
I'm running a custom function to convert it to an object. Only the top-level should be converted, the sub-arrays should stay as arrays. The output comes out like this:
stdClass Object
(
[price] => 700.00
[room_prices] => Array
(
[0] => Array
)
[bills] => Array
(
[0] => Array
)
)
Here is my conversion function. All it does is set the value of each array member to an object:
function array_to_object( $arr )
{
$obj = new stdClass;
if ( count($arr) == 0 )
return $obj;
foreach ( $arr as $k=>$v )
$obj->$k = $v;
return $obj;
}
I can't figure this out for the life of me!
© Stack Overflow or respective owner