Converting Array and Objects in Array to Pure Array in PHP

Last updated 1 week, 6 days ago | 36 views 75     5

Tags:- PHP

When working with PHP, you may encounter situations where you need to convert an array that contains stdClass objects into a pure multi-dimensional associative array. This is particularly useful when handling data from APIs or database queries. Here’s how to achieve this.

Method 1: Using json_encode() and json_decode()

This method leverages PHP’s JSON functions to handle the conversion efficiently.

$data = [
    (object) ['id' => 1, 'name' => 'John Doe'],
    (object) ['id' => 2, 'name' => 'Jane Smith'],
    (object) ['id' => 6, 'name' => 'Michael Johnson']
];

$pureArray = json_decode(json_encode($data), true);

print_r($pureArray);

Output

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => John Doe
        )

    [1] => Array
        (
            [id] => 2
            [name] => Jane Smith
        )

    [2] => Array
        (
            [id] => 6
            [name] => Michael Johnson
        )
)

Method 2: Using Recursive Conversion

If you want more control or avoid JSON functions, a recursive function can help:

function objectToArray($data) {
    if (is_object($data)) {
        $data = get_object_vars($data);
    }
    if (is_array($data)) {
        return array_map('objectToArray', $data);
    } else {
        return $data;
    }
}

$data = [
    (object) ['id' => 1, 'name' => 'John Doe'],
    (object) ['id' => 2, 'name' => 'Jane Smith'],
    (object) ['id' => 6, 'name' => 'Michael Johnson']
];

$pureArray = objectToArray($data);

print_r($pureArray);

Output

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => John Doe
        )

    [1] => Array
        (
            [id] => 2
            [name] => Jane Smith
        )

    [2] => Array
        (
            [id] => 6
            [name] => Michael Johnson
        )
)

Conclusion

  • Use json_decode() and json_encode() for a reliable and simple approach.

  • Type casting can work but may introduce unwanted keys for protected or private properties.

  • get_object_vars() is the cleanest solution when working with public properties.

  • The recursive function approach provides more control and avoids the overhead of JSON functions.

By selecting the appropriate method, you can efficiently convert PHP objects to associative arrays based on your project’s requirements.