Search code examples
phparrays

How to convert an stdClass to an array?


I have a problem to convert an object stdClass to array.

I have tried in this way:

return (array) $booking;

or

return (array) json_decode($booking,true);

or

return (array) json_decode($booking);

The array before the cast is full with one record, after my try to cast it is empty. How to cast / convert it without delete its rows?

array before cast:

array(1) {   [0]=>   object(stdClass)#23 (36) {     ["id"]=>     string(1) "2"     ["name"]=>     string(0) ""     ["code"]=>     string(5) "56/13"   } } 

after cast is empty NULL if I try to make a var_dump($booking);

I have also tried this function but always empty:

public function objectToArray($d) {
        if (is_object($d)) {
            // Gets the properties of the given object
            // with get_object_vars function
            $d = get_object_vars($d);
        }
 
        if (is_array($d)) {
            /*
            * Return array converted to object
            * Using __FUNCTION__ (Magic constant)
            * for recursive call
            */
            return array_map(__FUNCTION__, $d);
        }
        else {
            // Return array
            return $d;
        }
    }

Solution

  • The lazy one-liner method

    You can do this in a one liner using the JSON methods if you're willing to lose a tiny bit of performance (though some have reported it being faster than iterating through the objects recursively - most likely because PHP is slow at calling functions). "But I already did this" you say. Not exactly - you used json_decode on the array, but you need to encode it with json_encode first.

    Requirements

    The json_encode and json_decode methods. These are automatically bundled in PHP 5.2.0 and up. If you use any older version there's also a PECL library (that said, in that case you should really update your PHP installation. Support for 5.1 stopped in 2006.)


    Converting an array/stdClass -> stdClass

    $stdClass = json_decode(json_encode($booking));
    

    Converting an array/stdClass -> array

    The manual specifies the second argument of json_decode as:

    assoc
    When TRUE, returned objects will be converted into associative arrays.

    Hence the following line will convert your entire object into an array:

    $array = json_decode(json_encode($booking), true);