For single-dimensional arrays, you can utilize either casting or the get_object_vars function.
Casting:
$array = (array) $object;
get_object_vars:
$array = get_object_vars($object);
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.
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);
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); }
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!