Sunday, May 15, 2016

Convert stdClass Object to Array in PHP

http://carlofontanos.com/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
)
Checkout my other tutorials by following this link: TUTORIALS