How to Reliably Convert a PHP stdClass Object to an Array?

Susan Sarandon
Release: 2024-11-16 00:13:02
Original
381 people have browsed it

How to Reliably Convert a PHP stdClass Object to an Array?

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;
        }
    }
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template