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!
  1. PHP: Calculate Real Differences Between Two Dates or Timestamps
  2. PHP mb_ucfirst Make a String’s First Character Uppercase-Multibyte (UTF-8) Function
  3. PHP CLI Colors – PHP Class Command Line Colors (bash)
  4. PHP __DIR__, __FILE__, __FUNCTION__, __CLASS__, __METHOD__, __LINE__, __NAMESPACE__
  5. Format bytes with PHP – B, KB, MB, GB, TB, PB, EB, ZB, YB converter

11 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);

  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 !

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