Convert stdClass Object to Array in PHP

Date Posted: September 2, 2014, 1:51 am


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
)

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me