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:
-
Explicit Type Casting: Simply casting the object to an array using (array) preserves all object properties, including private and protected members.
$array = (array) $object;
-
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);
Multi-Dimensional Arrays
Converting multi-dimensional arrays requires a slightly different approach.
-
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);
-
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;
}
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!
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