Home >Backend Development >PHP Tutorial >How Can I Convert a PHP Object to an Array?

How Can I Convert a PHP Object to an Array?

DDD
DDDOriginal
2024-12-09 10:30:05656browse

How Can I Convert a PHP Object to an Array?

Converting an Object to an Array in PHP

Objects in PHP represent complex data structures, while arrays are indexed collections. To convert an object to an array, the appropriate method must be selected based on the dimensionality of the desired array.

Single-Dimensional Arrays

For single-dimensional arrays, two approaches are commonly used:

  • (array) Cast:

    $array = (array) $object;
  • get_object_vars:

    $array = get_object_vars($object);

The main difference between these methods lies in how they treat object properties. get_object_vars only returns public properties, while (array) casts all properties, including private and protected, to an array.

Multi-Dimensional Arrays

Converting multi-dimensional objects to arrays presents a greater challenge. One possible solution is to utilize PHP's JSON functions:

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

However, this method excludes private and protected properties and is unsuitable for objects containing non-JSON-encodable data.

An alternative approach is to employ the following function, which recursively converts object properties into an array:

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

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

This function ensures that all object properties, including private and protected, are included in the resulting array.

The above is the detailed content of How Can I Convert a PHP Object to an Array?. 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