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
)