Home >Backend Development >PHP Tutorial >How Can I Convert PHP Objects into Arrays?

How Can I Convert PHP Objects into Arrays?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-12 11:15:10512browse

How Can I Convert PHP Objects into Arrays?

Converting Objects to Arrays

Objects in PHP can be converted into arrays to facilitate easier manipulation and data retrieval. Here are three methods to achieve this conversion:

Single-Dimensional Arrays

  • Array Casting: Using (array) will cast an object into an array, including all public, private, and protected members.
$array = (array) $object;
  • get_object_vars Function: This function returns an array containing only the publicly accessible properties of an object unless called from within the object's scope.
$array = get_object_vars($object);

Multi-Dimensional Arrays

To convert multi-dimensional objects, the following approaches can be used:

  • JSON Encoding and Decoding: By encoding the object to JSON and then decoding it back as an array, you can obtain a multi-dimensional array. Note that this method excludes private and protected members and is not suitable for objects containing non-JSON-encodable data.
$array = json_decode(json_encode($object), true);
  • ObjectToArray Function: This custom 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);
}

By utilizing these methods, you can effectively convert PHP objects into arrays for various use cases, enabling seamless data manipulation and retrieval.

The above is the detailed content of How Can I 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