Home >Backend Development >PHP Tutorial >How to Efficiently Convert a PHP stdClass Object to an Array?
Question:
I need to convert a PHP stdClass object into an array. However, attempts using (array) casting, json_decode(true), and json_decode() have resulted in an empty array. How can I perform this conversion effectively?
Answer:
For a slightly compromised performance, you can leverage the JSON methods to achieve this conversion in a concise manner:
$array = json_decode(json_encode($booking), true);
This method first encodes the object into a JSON string and then decodes it back into an array.
$array = (array) json_decode(json_encode($booking));
This approach returns an indexed array without preserving property names.
$array = json_decode(json_encode($booking), true);
By passing true as the second argument to json_decode, you can convert the object into an associative array, preserving property names.
If performance is critical, you can implement a custom recursive function to convert the object to an array:
function object_to_array($object) { if (is_object($object)) { $object = get_object_vars($object); } if (is_array($object)) { return array_map(__FUNCTION__, $object); } else { return $object; } } $array = object_to_array($booking);
The above is the detailed content of How to Efficiently Convert a PHP stdClass Object to an Array?. For more information, please follow other related articles on the PHP Chinese website!