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

How Can I Effectively Convert a PHP Object into an Array?

Linda Hamilton
Release: 2024-12-10 02:52:13
Original
994 people have browsed it

How Can I Effectively Convert a PHP Object into an Array?

How to Effectively Convert an Object into an Array Format

Within PHP, you may encounter situations where an object needs to be converted into an array format. This article delves into various techniques to achieve this conversion.

Single-Dimensional Arrays

Two methods are often used to convert single-dimension arrays:

  1. Explicit Type Casting: Simply casting the object to an array using (array) preserves all object properties, including private and protected members.
$array = (array) $object;
Copy after login
  1. get_object_vars(): This function retrieves an array containing only publicly accessible properties. In object scope, it includes all properties.
$array = get_object_vars($object);
Copy after login

Multi-Dimensional Arrays

Converting multi-dimensional arrays requires a slightly different approach.

  1. JSON Encoding and Decoding: This method is compatible with PHP 5.2 or later. JSON encoding converts the object to a JSON string, which is then decoded back into an associative array. However, this approach does not handle private and protected members or objects containing un-JSON-encodable data.
$array = json_decode(json_encode($object), true);
Copy after login
  1. Custom Function: The following function, based on a modified version found elsewhere, provides a more comprehensive option:
function objectToArray($object) {
    if (is_object($object) || is_array($object)) {
        return array_map('objectToArray', (array) $object);
    }
    return $object;
}
Copy after login

This function recursively converts all object properties into an array format, regardless of access modifiers.

The above is the detailed content of How Can I Effectively Convert a PHP Object into an Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template