PHP stdClass to Array and Array to stdClass – stdClass Object

I think every PHP coders have come accross Arrays and stdClass Objects (belongs to PHP Predefined Classes). Sometimes it’s very useful convert Objects to Arrays and Arrays to Objects. This is easy if arrays and objects are one-dimensional, but might be little tricky if using multidimensional arrays and objects.

This post defines two ultra simple recursive function to convert multidimensional Objects to Arrays and multidimensional Arrays to Objects.

Function to Convert stdClass Objects to Multidimensional Arrays

<?php
 
	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;
		}
	}
 
?>

Function to Convert Multidimensional Arrays to stdClass Objects

<?php
 
	function arrayToObject($d) {
		if (is_array($d)) {
			/*
			* Return array converted to object
			* Using __FUNCTION__ (Magic constant)
			* for recursive call
			*/
			return (object) array_map(__FUNCTION__, $d);
		}
		else {
			// Return object
			return $d;
		}
	}
 
?>

Function usage

	// Create new stdClass Object
	$init = new stdClass;
 
	// Add some test data
	$init->foo = "Test data";
	$init->bar = new stdClass;
	$init->bar->baaz = "Testing";
	$init->bar->fooz = new stdClass;
	$init->bar->fooz->baz = "Testing again";
	$init->foox = "Just test";
 
	// Convert array to object and then object back to array
	$array = objectToArray($init);
	$object = arrayToObject($array);
 
	// Print objects and array
	print_r($init);
	echo "\n";
	print_r($array);
	echo "\n";
	print_r($object);

Test output:

stdClass Object
(
    [foo] => Test data
    [bar] => stdClass Object
        (
            [baaz] => Testing
            [fooz] => stdClass Object
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

Array
(
    [foo] => Test data
    [bar] => Array
        (
            [baaz] => Testing
            [fooz] => Array
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

stdClass Object
(
    [foo] => Test data
    [bar] => stdClass Object
        (
            [baaz] => Testing
            [fooz] => stdClass Object
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)
Follow If Not True Then False Updates!

49 Comments

  1. Enjoying reading the posts here, thanks.

  2. thanks very much..
    very useful for me , I have just started to learn OOP , and using objects is difficult for me initially ;)
    thanks again :D

  3. Thanks a lot for your first function :)

  4. Muitissimo obrigado.
    Cara tu não imagina a felicidade de eu conectar no meu servidor java aqui com PHP.

    Vlw =D

  5. Thanks!

    I use this methods to data from json_decode function to get an array.

    • set the 3. parameter of json_decode to true to archive the same.

      • its the second parameter, sorry

  6. very nice to get it

    thanx a tonn

  7. Hi, in reference to what your using it for La5, you should just pass true as the second variable of json_decode to get it to return an associative array

    eg:

    $json =’{ “blah”:”bleh”}’;
    json_decode($json, TRUE);

    • Thanks pretty kool, saved a lot of time :)

  8. Thank you, it’s clean, documented, and working!

  9. Nice! This is quite handy.

  10. Thanks for the input. yes, it works.I give you ten

  11. Merci beaucoup !

  12. Very rarely am I able to copy and paste a block of code and have it work. WOW! You hit the nail on the head and helped me after a very frustrating day.

    Thanks

  13. You saved my day. This code it directly to the point.
    Really good work.

  14. Congratulations. Simple and efficient.

  15. Very Usefull

  16. Yes thank you however I ran into a problem if I was converting XML -> object -> array and there is a group of items that could have multiples but only has 1 it will return differently based on the amount of data. Not sure how you can fix this but I had to put in a switch and handle things differently if there was 1 or more than 1 item.

  17. Function to Convert stdClass Objects to Multidimensional Arrays, working very well.

  18. Or you could typecast (object)$array; and (array)$stdClass; which will do the conversion, see PHP Manual for objects. Just for people googling.

  19. That just typecase first level of object.

  20. Yes, that is the problem with typecasting. However since writing this post I found that it is quite possible to utilize objects much the same way you would an array. So for instance you can foreach through a specific object. This seemed to negate the need for me to convert to arrays as that was the only real reason I was doing it. I guess I wish that object syntax was better explained at php.net as well as the functions that can use both arrays and objects.

  21. But RESTful web services sometimes return array as first level of response then inside it has stdClass. and many times when it return only one item then it return just stdClass.

  22. Well I don’t know about “most” RESTful services returning this but an array of objects appears pretty predictable on how to handle. You can make sure your code parses the object and then iterate through the array parse each object in turn.

    $var = restReturnValues();

    foreach ($var as $v) {
    $var2 = $v->objProp

    }

  23. how do I format is back to HTML?

  24. Is there a way to combine two or more arrays and create one object. One of the arrays being an array of arrays.

    Example

    Array ( [Story reality] => fantacy [Story type] => Comedy [Story conflict] => Man vs Nature [Time] => Prehistoric [Occupation] => Corporate [Society] => Dystopia [Time needed] => Long [Recommended age] => Kinds and over [Difficulty] => Medium commitment )
    Array ( [tone] => Array ( [0] => Positive [1] => Logical ) [primary] => Array ( [0] => Drama [1] => Coming of age ) [second] => Array ( [0] => Courage Fear [1] => Jealousy [2] => Gender inequality ) [torchtag] => Array ( [0] => Animation ) )

    • Appending arrays is fairly simple, what would you want it to look like when you are done?

  25. thanks.. great peace of code..

  26. This is really great. Works like a Charm with one standard class object in the array. How do you do this when the array looks like this with multiple objects and offsets?

    stdClass Object ( [FlightInfoExResult] => stdClass Object ( [next_offset] => 1 [flights] => stdClass Object ( [faFlightID] => N220TX-1349554522-76-0 [ident] => N220TX [aircrafttype] => SR22 [filed_ete] => 02:01:00 [filed_time] => 1349559840 [filed_departuretime] => 1349561700 [filed_airspeed_kts] => 162 [filed_airspeed_mach] => [filed_altitude] => 70 [route] => IRW GREGS6 [actualdeparturetime] => 1349561340 [estimatedarrivaltime] => 1349568227 [actualarrivaltime] => 1349568000 [diverted] => [origin] => KEWK [destination] => KADS [originName] => Newton-City-County [originCity] => Newton, KS [destinationName] => Addison [destinationCity] => Dallas, TX ) ) )

    • Hi Kristopher,

      This is not problem, exactly same functions works with multidimensional objects/arrays, check following:

      <?php
       
      	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;
      		}
      	}
       
      	$temp = new stdClass;
      	$temp->FlightInfoExResult = new stdClass;
      	$temp->FlightInfoExResult->next_offset = 1;
      	$temp->FlightInfoExResult->flights = new stdClass;
      	$temp->FlightInfoExResult->flights->faFlightID = "N220TX-1349554522-76-0";
      	$temp->FlightInfoExResult->flights->ident = "N220TX";
      	$temp->FlightInfoExResult->flights->aircrafttype = "SR22";
      	$temp->FlightInfoExResult->flights->filed_ete = "02:01:00";
      	$temp->FlightInfoExResult->flights->filed_time = 1349559840;
      	$temp->FlightInfoExResult->flights->filed_departuretime = 1349561700;
      	$temp->FlightInfoExResult->flights->filed_airspeed_kts = 162;
      	$temp->FlightInfoExResult->flights->filed_altitude = "";
      	$temp->FlightInfoExResult->flights->route = "IRW GREGS6";
      	$temp->FlightInfoExResult->flights->actualdeparturetime = 1349561340;
      	$temp->FlightInfoExResult->flights->estimatedarrivaltime = 1349568227;
      	$temp->FlightInfoExResult->flights->actualarrivaltime = 1349568000;
      	$temp->FlightInfoExResult->flights->diverted = "";
      	$temp->FlightInfoExResult->flights->origin = "KEWK";
      	$temp->FlightInfoExResult->flights->destination = "KADS";
      	$temp->FlightInfoExResult->flights->originName = "Newton-City-County";
      	$temp->FlightInfoExResult->flights->originCity = "Newton, KS";
      	$temp->FlightInfoExResult->flights->destinationName = "Addison";
      	$temp->FlightInfoExResult->flights->destinationCity = "Dallas, TX"; 
       
      	print_r($temp);
       
      	print_r(objectToArray($temp));

      Output:

      stdClass Object
      (
          [FlightInfoExResult] => stdClass Object
              (
                  [next_offset] => 1
                  [flights] => stdClass Object
                      (
                          [faFlightID] => N220TX-1349554522-76-0
                          [ident] => N220TX
                          [aircrafttype] => SR22
                          [filed_ete] => 02:01:00
                          [filed_time] => 1349559840
                          [filed_departuretime] => 1349561700
                          [filed_airspeed_kts] => 162
                          [filed_altitude] => 
                          [route] => IRW GREGS6
                          [actualdeparturetime] => 1349561340
                          [estimatedarrivaltime] => 1349568227
                          [actualarrivaltime] => 1349568000
                          [diverted] => 
                          [origin] => KEWK
                          [destination] => KADS
                          [originName] => Newton-City-County
                          [originCity] => Newton, KS
                          [destinationName] => Addison
                          [destinationCity] => Dallas, TX
                      )
       
              )
       
      )
      Array
      (
          [FlightInfoExResult] => Array
              (
                  [next_offset] => 1
                  [flights] => Array
                      (
                          [faFlightID] => N220TX-1349554522-76-0
                          [ident] => N220TX
                          [aircrafttype] => SR22
                          [filed_ete] => 02:01:00
                          [filed_time] => 1349559840
                          [filed_departuretime] => 1349561700
                          [filed_airspeed_kts] => 162
                          [filed_altitude] => 
                          [route] => IRW GREGS6
                          [actualdeparturetime] => 1349561340
                          [estimatedarrivaltime] => 1349568227
                          [actualarrivaltime] => 1349568000
                          [diverted] => 
                          [origin] => KEWK
                          [destination] => KADS
                          [originName] => Newton-City-County
                          [originCity] => Newton, KS
                          [destinationName] => Addison
                          [destinationCity] => Dallas, TX
                      )
       
              )
       
      )
  27. You are absolutely correct! I had made a mistake! You are awesome!!!

    • Excellent! Thank you! :)

  28. Its nice article.Here below i give sample object array, how to convert to array.
    stdClass Object
    (
    [RecordReference] => Science
    [NotificationType] => 03
    [ProductIdentifier] => Array
    (
    [0] => stdClass Object
    (
    [ProductIDType] => 15
    [IDValue] => 9781608051137
    )

    [1] => stdClass Object
    (
    [ProductIDType] => 01
    [IDTypeName] => ONIX_Science
    [IDValue] => stdClass Object
    (
    )

    )

    )

    [ProductForm] => DG
    [EpubType] => 01
    [NoSeries] => stdClass Object
    (
    )

    [Title] => stdClass Object
    (
    [TitleType] => 01
    [TitleText] => Biology
    )

    [Contributor] => stdClass Object
    (
    [SequenceNumber] => 1
    [ContributorRole] => A01
    [PersonName] => test
    )

    [NoEdition] => stdClass Object
    (
    )

    [Language] => stdClass Object
    (
    [LanguageRole] => 01
    [LanguageCode] => eng
    )

    [Extent] => stdClass Object
    (
    [ExtentType] => 22
    [ExtentValue] => 2.78 MB
    [ExtentUnit] => 19
    )

    [BASICMainSubject] => MED016000
    [MainSubject] => stdClass Object
    (
    [MainSubjectSchemeIdentifier] => 20
    [SubjectHeadingText] => Medical & Heath Sciences
    )

    [OtherText] => stdClass Object
    (
    [TextTypeCode] => 01
    [Text] => This textbook provides a comprehensive overview of the part of dentistry that links basic physiologic and pathophysiologic mechanisms to frequently encountered problems in dental practice.
    )

    [Imprint] => stdClass Object
    (
    [NameCodeType] => 01
    [NameCodeValue] => test
    )

    [Publisher] => stdClass Object
    (
    [PublishingRole] => 01
    [PublisherName] => Science Publishers
    )

    [PublicationDate] => 2010
    [SupplyDetail] => stdClass Object
    (
    [SupplierName] => Science
    [SupplierRole] => 00
    [ProductAvailability] => 20
    [PackQuantity] => S
    [Price] => stdClass Object
    (
    [PriceTypeCode] => 01
    [PriceAmount] => 34
    [CurrencyCode] => USD
    )

    )

    )

    • Hi Sundar,

      objectToArray function should work?

  29. Thank you, this is exactly what I was looking for!

  30. Thanks for the function man. I was running into problems using these in a MVC framework, swapping __FUNCTION__ for __METHOD__ for the callback target was the golden ticket for me.

    Thanks again.

  31. Thanks,

  32. I’ve always just done this: $array = (array)$object;

    • Hi Nigell,

      As I said at the beginning, this is easy if arrays and objects are one-dimensional. Your method doesn’t work with multidimensional arrays and objects.

      Try following:

      <?php
       
              $init = new stdClass;
       
              // Add some test data
              $init->foo = "Test data";
              $init->bar = new stdClass;
              $init->bar->baaz = "Testing";
              $init->bar->fooz = new stdClass;
              $init->bar->fooz->baz = "Testing again";
              $init->foox = "Just test";
       
              print_r((array)$init);

      Output:

      Array
      (
          [foo] => Test data
          [bar] => stdClass Object
              (
                  [baaz] => Testing
                  [fooz] => stdClass Object
                      (
                          [baz] => Testing again
                      )
      
              )
      
          [foox] => Just test
      )
      

      First dimension is converted to array, but all others are still stdClass Objects, right?

      When you use objectToArray function output looks following:

      Array
      (
          [foo] => Test data
          [bar] => Array
              (
                  [baaz] => Testing
                  [fooz] => Array
                      (
                          [baz] => Testing again
                      )
      
              )
      
          [foox] => Just test
      )
      

      All stdClass Objects are converted to arrays.

  33. Really appreciate this post! Helped me a lot! :)

  34. Thank you so much for this post, you saved me countless hours!!!

  35. Thanks…………. it’s save my time.

  36. Thank you so must for posting this. You made my Sunday night coding not as bad as it could have been.

  37. You don’t really need all this :-)
    Typecasting works!

    Try:

    $tmp = array("test" => "test");
    var_dump((object)$tmp);
    var_dump((array)(object)$tmp);

    • Hi Tobi,

      Run following to see difference with typecasting and arrayToObject function:

      <?php
       
              function arrayToObject($d) {
                      if (is_array($d)) {
                              /*
                              * Return array converted to object
                              * Using __FUNCTION__ (Magic constant)
                              * for recursive call
                              */
                              return (object) array_map(__FUNCTION__, $d);
                      }
                      else {
                              // Return object
                              return $d;
                      }
              }
       
              $tmp = array("test" => array("test" => "test","test2" => "test2"));
       
              var_dump((object)$tmp);
       
              var_dump(arrayToObject($tmp));

      Typecasting won’t work (unfortunately) with multidimensional arrays.

  38. THANKSSSS! great job!!!

    If someone needs this method inside a static class change the line… return array_map(__FUNCTION__, $d); for this one return array_map([__CLASS__, __METHOD__], $d);

  39. Hello Tobi,
    Thank you thanky you!!
    You helped me so much

  40. no need for and of that.

    $a = array(‘key’ => ‘value’, ‘another key’ => ‘another value’);

    var_dump(json_decode(json_encode($a)));

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>