Convert stdClass Object to Array in PHP

Use this function to convert stdClass Objects into Arrays:

1
2
3
4
5
6
7
8
9
10
11
12
13
function cvf_convert_object_to_array($data) {

    if (is_object($data)) {
        $data = get_object_vars($data);
    }

    if (is_array($data)) {
        return array_map(__FUNCTION__, $data);
    }
    else {
        return $data;
    }
}

Test Results:

stdClass Object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
stdClass Object
(
    [foo] => Test data
    [bar] => stdClass Object
        (
            [baaz] => Testing
            [fooz] => stdClass Object
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

Converted to Array:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Array
(
    [foo] => Test data
    [bar] => Array
        (
            [baaz] => Testing
            [fooz] => Array
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)


Do you need help with a project? or have a new project in mind that you need help with?

Contact Me