PHP stdClass to Array and Array to stdClass – stdClass Object - Comment Page: 2

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. [inttf_post_ad1] Function to Convert stdClass Objects to Multidimensional Arrays <?php function objectToArray($d) { if (is_object($d)) { // Gets the properties of the given object ...

61 comments on “PHP stdClass to Array and Array to stdClass – stdClass Object - Comment Page: 2

1 2 3 4
    1. 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.

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

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

      Reply
    4. That just typecase first level of object.

      Reply
    5. 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.

      Reply
    6. 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.

      Reply
    7. 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

      }

      Reply
    8. how do I format is back to HTML?

      Reply
    9. 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 ) )

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

        Reply
    10. thanks.. great peace of code..

      Reply
    11. 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 ) ) )

      Reply
      • 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
                        )
        
                )
        
        )
        
        
        Reply
    12. You are absolutely correct! I had made a mistake! You are awesome!!!

      Reply
      • Excellent! Thank you! :)

        Reply
    13. 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
      )

      )

      )

      Reply
      • Hi Sundar,

        objectToArray function should work?

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

      Reply
    15. 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.

      Reply
1 2 3 4

Leave a Reply to Goga Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Close