php stdClass to array
When working with PHP, you may encounter the need to convert an stdClass object to an array. This conversion can be tricky, and different methods may result in unexpected behavior.
One common approach is to cast the object to an array using (array) $booking. However, this method may result in an empty array if the object contains any nested objects or arrays.
Another option is to use json_decode($booking, true). This method will convert the object to an array, but it may also result in an empty array if the object contains any nested objects or arrays.
A more reliable method for converting an stdClass object to an array is to use a recursive function that iterates through the object and its children, converting each element to its corresponding array representation. Here is an example of such a function:
public function objectToArray($d) { if (is_object($d)) { // Gets the properties of the given object // with get_object_vars function $d = get_object_vars($d); } if (is_array($d)) { /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return array_map(__FUNCTION__, $d); } else { // Return array return $d; } }
This function will convert an stdClass object into an array, preserving the structure and values of the original object. It can also be used to convert arrays into objects if desired.
The above is the detailed content of How to Reliably Convert a PHP stdClass Object to an Array?. For more information, please follow other related articles on the PHP Chinese website!