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
)
e-mail
Follow If Not True Then False Updates!

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

  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?

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> <pre lang="" line="" escaped="" highlight="">

Bear