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

How to Effectively Convert PHP Objects into Arrays?

Linda Hamilton
Release: 2024-12-07 15:23:12
Original
398 people have browsed it

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;
Copy after login

get_object_vars:

$array = get_object_vars($object);
Copy after login

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);
Copy after login

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);
}
Copy after login

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!

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