Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question

2 Answers 2

up vote 3 down vote accepted

I can't reproduce (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));

gives

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

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

)
share|improve this answer
    
Thanks for the response. I checked the output right after the function and realised the function is working correctly! There was another part of my code modifying the output afterwards. One of those faceslap moments. –  DisgruntledGoat May 14 '10 at 16:09

why don't you just cast the array to an object?

$myObj = (object) $myArray;
share|improve this answer
    
Interesting, didn't realise that would work. –  DisgruntledGoat May 14 '10 at 16:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.