Transforming an object into an array in PHP is a common requirement when dealing with data structures. This article provides an in-depth guide to achieve this conversion efficiently.
To convert a single-dimensional object to an array, you can utilize two methods:
Converting multi-dimensional objects to arrays requires a different approach. Here are two commonly used methods:
JSON Encoding and Decoding
Recursive Conversion Function
Example:
function objectToArray($object) { if(!is_object($object) && !is_array($object)) return $object; return array_map('objectToArray', (array) $object); }
This function will convert an object with private and protected members into a multi-dimensional array.
The above is the detailed content of How Can I Efficiently Convert PHP Objects to Arrays?. For more information, please follow other related articles on the PHP Chinese website!