Home >Backend Development >PHP Tutorial >How to Effectively Convert PHP Objects into Arrays?

How to Effectively Convert PHP Objects into Arrays?

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 15:23:12399browse

How to Effectively Convert PHP Objects into Arrays?

How to Convert an Object to an Array

Single-Dimensional Arrays

For single-dimensional arrays, you can utilize either casting or the get_object_vars function.

Casting:

$array = (array) $object;

get_object_vars:

$array = get_object_vars($object);

While both methods convert an object to an array, they exhibit subtle differences. get_object_vars only returns publicly accessible properties, unless called within the object's scope. Casting, however, preserves all members, including private and protected ones.

Multi-Dimensional Arrays

For multi-dimensional arrays, you can employ various approaches.

JSON Encoding and Decoding:

If your object can be encoded as JSON, you can use PHP's native JSON functions:

$array = json_decode(json_encode($object), true);

This method doesn't include private and protected members and is not suitable for objects containing non-JSON-encodable data.

Recursive Function:

The following function recursively converts an object to an array, including private and protected members:

function objectToArray($object) {
    if(!is_object($object) && !is_array($object))
        return $object;

    return array_map('objectToArray', (array) $object);
}

The above is the detailed content of How to Effectively Convert PHP Objects into Arrays?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn