271

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;
        }
    }
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
  • http://php.net/var_dump ... http://php.net/var_export - before `return`. And running [`json_decode`](http://php.net/json_decode) on an array seems pretty desperate to me, probably sitting too long in front of the computer and it's now time to take a break? – hakre Sep 02 '13 at 15:41
  • Just to clarify: `var_dump($booking);` outputs `NULL`? – hakre Sep 02 '13 at 15:44
  • after cast yes, and if i try to print this: $booking[0]['id'] return me that not exist – Alessandro Minoccheri Sep 02 '13 at 15:44
  • You might be interested to read: [How to get useful error messages in PHP?](http://stackoverflow.com/q/845021/367456) - Anyway, I was asking to `var_dump()` *before* casting. Do not re-use the same variable name btw. if `$booking` was something before casting, it should still be that something *before* casting and not something different afterwards. Differ between input and processing variables otherwise you run into problems that you don't understand any longer what you do there. – hakre Sep 02 '13 at 15:47
  • Shortening the question (like removing the custom function code) could be useful to see the accepted answer without having to scroll down – cnlevy Dec 29 '15 at 19:12
  • In the general case, I think this is not possible. Consider if your objects have cycles, dereferencing this into arrays, will end up in an infinite loop... Just wanted to point this issue. For other scenarios, other answers are certainly valid... – Vincent Pazeller Oct 04 '18 at 13:03

11 Answers11

555

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);
h2ooooooo
  • 39,111
  • 8
  • 68
  • 102
  • 1
    If `(array) $booking;` in a `var_dump` is `NULL` (as written by OP), guess what this code will return? – hakre Sep 02 '13 at 15:50
  • @hakre It doesn't seem like it's `NULL` after casting it as an array. I think OP means that it's `NULL` after using `json_decode($array)` which makes sense per the [manual](http://php.net/manual/en/function.json-decode.php). *NULL is returned if the json cannot be decoded* – h2ooooooo Sep 02 '13 at 15:52
  • In the question there are outlined three ways. OP as given the `NULL` information for all three ways. – hakre Sep 02 '13 at 15:53
  • 4
    @AlessandroMinoccheri The reason it didn't work before was before you were using `json_decode()` on an array. `json_decode` should be used on a JSON string. Therefore, if we encode it as a JSON string first (`json_encode`) and **then** decode it (using our JSON string), then it works fine. – h2ooooooo Sep 02 '13 at 15:56
  • I have accpeted the other question because I think is better, but your solution is fine thanks a lot – Alessandro Minoccheri Sep 02 '13 at 15:58
  • @AlessandroMinoccheri No problem - it might (*read: should*) be quicker any way, and this is, as said, just the lazy solution. – h2ooooooo Sep 02 '13 at 15:58
  • Thanks for explain why is better and I have make a benchmark and it's very fast than the other methods. Thanks @h2ooooooo – Alessandro Minoccheri Dec 27 '13 at 14:50
  • 4
    Has everyone forgot that you will lose your types that are not defined in JSON spec (dates for example)? You'll need to have a reviver then if you use this approach. This is only good if you have basic types such as numbers, strings and booleans. – Denis Pshenov Nov 03 '14 at 14:13
  • 1
    Great answer, I've been just using json_decode($stdClass, true) ;) – didando8a Nov 25 '15 at 10:03
  • this answer was very useful in explaining some stuff I didn't know but the encode before is not always necessary, in fact sometimes it converts the data into a string. Recently, the solution for me was just json_decode($stdClass, true); – Michael Tunnell Jun 02 '16 at 20:25
  • The line that work for me was json_decode(json_encode($booking), true); – dani24 Sep 21 '16 at 15:25
111

use this function to get a standard array back of the type you are after...

return get_object_vars($booking);
robzero
  • 1,135
  • 1
  • 7
  • 2
55

Use the built in type cast functionality, simply type

$realArray = (array)$stdClass;
David Clews
  • 795
  • 6
  • 14
  • 3
    I prefer this over json_decode/encode, much cleaner +1 – Logan Oct 10 '19 at 19:31
  • 8
    This method is cleaner, however, it's also not recursive, and works the same as the get_object_vars(). While the json_decode/encode method has the feel of a hack, it works recursively. – Debbie V Oct 29 '19 at 15:23
  • 2
    If you have multiple depth objects only the first elements get type cast to an array. n+ deep elements will be still objects. So using json_encode/decode fixes that. – Gkiokan Jul 07 '22 at 15:47
20

Since it's an array before you cast it, casting it makes no sense.

You may want a recursive cast, which would look something like this:

function arrayCastRecursive($array)
{
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $array[$key] = arrayCastRecursive($value);
            }
            if ($value instanceof stdClass) {
                $array[$key] = arrayCastRecursive((array)$value);
            }
        }
    }
    if ($array instanceof stdClass) {
        return arrayCastRecursive((array)$array);
    }
    return $array;
}

Usage:

$obj = new stdClass;
$obj->aaa = 'asdf';
$obj->bbb = 'adsf43';
$arr = array('asdf', array($obj, 3));

var_dump($arr);
$arr = arrayCastRecursive($arr);
var_dump($arr);

Result before:

array
    0 => string 'asdf' (length = 4)
  1 => 
    array
        0 =>
        object(stdClass)[1]
          public 'aaa' => string 'asdf' (length = 4)
          public 'bbb' => string 'adsf43' (length = 6)
      1 => int 3

Result after:

array
    0 => string 'asdf' (length = 4)
  1 => 
    array
        0 =>
        array
          'aaa' => string 'asdf' (length = 4)
          'bbb' => string 'adsf43' (length = 6)
      1 => int 3

Note:

Tested and working with complex arrays where a stdClass object can contain other stdClass objects.

Vlad Preda
  • 9,780
  • 7
  • 36
  • 63
17

This function worked for me:

function cvf_convert_object_to_array($data) {

    if (is_object($data)) {
        $data = get_object_vars($data);
    }

    if (is_array($data)) {
        return array_map(__FUNCTION__, $data);
    }
    else {
        return $data;
    }
}

Reference: http://carlofontanos.com/convert-stdclass-object-to-array-in-php/

Carlo Fontanos
  • 422
  • 4
  • 10
16

Please use following php function to convert php stdClass to array

get_object_vars($data)
slfan
  • 8,950
  • 115
  • 65
  • 78
Nalantha
  • 169
  • 1
  • 2
4

Just googled it, and found here a handy function that is useful for converting stdClass object to array recursively.

<?php
function object_to_array($object) {
 if (is_object($object)) {
  return array_map(__FUNCTION__, get_object_vars($object));
 } else if (is_array($object)) {
  return array_map(__FUNCTION__, $object);
 } else {
  return $object;
 }
}
?>

EDIT: I updated this answer with content from linked source (which is also changed now), thanks to mason81 for suggesting me.

shasi kanth
  • 6,987
  • 24
  • 106
  • 158
  • 1
    Next time please include the relevant content from the linked source. The link you provided has changed and is now irrelevant and useless. – mason81 Oct 24 '14 at 16:46
  • This is what I was looking for, Thank you so much. –  Dec 24 '18 at 05:39
1

Here's how I use it in Laravel without Eloquent.

function getUsers(){ 

   $users = DB::select('select * from users');       
   $data = json_decode(json_encode($users), true); // to array 

   return view('page')->with('data', $data);
}
incalite
  • 3,077
  • 3
  • 26
  • 32
0

Here is a version of Carlo's answer that can be used in a class:

class Formatter
{
    public function objectToArray($data)
    {
        if (is_object($data)) {
            $data = get_object_vars($data);
        }

        if (is_array($data)) {
            return array_map(array($this, 'objectToArray'), $data);
        }

        return $data;
    }
}
Loren
  • 9,783
  • 4
  • 39
  • 49
0

The following code will read all emails & print the Subject, Body & Date.

<?php
  $imap=imap_open("Mailbox","Email Address","Password");
  if($imap){$fixMessages=1+imap_num_msg($imap);  //Check no.of.msgs
/*
By adding 1 to "imap_num_msg($imap)" & starting at $count=1
   the "Start" & "End" non-messages are ignored
*/
    for ($count=1; $count<$fixMessages; $count++){
      $objectOverview=imap_fetch_overview($imap,$count,0);
print '<br>$objectOverview: '; print_r($objectOverview);
print '<br>objectSubject ='.($objectOverview[0]->subject));
print '<br>objectDate ='.($objectOverview[0]->date);
      $bodyMessage=imap_fetchbody($imap,$count,1);
print '<br>bodyMessage ='.$bodyMessage.'<br><br>';
    }  //for ($count=1; $count<$fixMessages; $count++)
  }  //if($imap)
  imap_close($imap);
?>

This outputs the following:

$objectOverview: Array ( [0] => stdClass Object ( [subject] => Hello
[from] => Email Address [to] => Email Address [date] => Sun, 16 Jul 2017 20:23:18 +0100
[message_id] =>  [size] => 741 [uid] => 2 [msgno] => 2 [recent] => 0 [flagged] => 0 
[answered] => 0 [deleted] => 0 [seen] => 1 [draft] => 0 [udate] => 1500232998 ) )
objectSubject =Hello
objectDate =Sun, 16 Jul 2017 20:23:18 +0100
bodyMessage =Test 

Having struggled with various suggestions I have used trial & error to come up with this solution. Hope it helps.

walter1957
  • 49
  • 1
  • 10
0

Here is the best Object to Array function I have - works recursively:

function object_to_array($obj, &$arr){
    
    if(!is_object($obj) && !is_array($obj)){
        $arr = $obj;
        return $arr;
    }
    
    foreach ($obj as $key => $value) {
        if (!empty($value)) {
            $arr[$key] = array();
            object_to_array_v2($value, $arr[$key]);
        } else {
            $arr[$key] = $value;
        }
    }

    return $arr;
}

$clean_array = object_to_array($object_data_here);
D. Schreier
  • 1,700
  • 1
  • 22
  • 34
nsdb
  • 130
  • 1
  • 6