将数组添加到对象会破坏数组

时间:2010-05-14 15:18:40

标签: php arrays object

我有一个这样的数组(从print_r输出):

Array
(
    [price] => 700.00
    [room_prices] => Array
        (
            [0] => 
            [1] => 
            [2] => 
            [3] => 
            [4] => 
        )

    [bills] => Array
        (
            [0] => Gas
        )
)

我正在运行自定义函数将其转换为对象。只应转换顶级,子数组应保持为数组。输出结果如下:

stdClass Object
(
    [price] => 700.00
    [room_prices] => Array
        (
            [0] => Array
        )

    [bills] => Array
        (
            [0] => Array
        )
)

这是我的转换功能。它所做的就是将每个数组成员的值设置为一个对象:

function array_to_object( $arr )
{
    $obj = new stdClass;
    if ( count($arr) == 0 )
        return $obj;

    foreach ( $arr as $k=>$v )
        $obj->$k = $v;

    return $obj;
}

我无法想象我的生活!

2 个答案:

答案 0 :(得分:4)

为什么不只是cast the array to an object

$myObj = (object) $myArray;

答案 1 :(得分:3)

我无法重现(PHP 5.3):

$a = array(
    "price" =>  700.00,
    "room_price" => array(NULL, NULL, NULL, NULL, NULL),
    bills => array("Gas"),
);

function array_to_object( $arr )
{
    $obj = new stdClass;
    if ( count($arr) == 0 )
        return $obj;

    foreach ( $arr as $k=>$v )
        $obj->$k = $v;

    return $obj;
}

print_r(array_to_object($a));

给出

stdClass Object
(
    [price] => 700
    [room_price] => Array
        (
            [0] =>
            [1] =>
            [2] =>
            [3] =>
            [4] =>
        )

    [bills] => Array
        (
            [0] => Gas
        )

)