What is the best way to convert objects to arrays in PHP to avoid potential issues with nested objects?

When converting objects to arrays in PHP, it's important to handle nested objects properly to avoid potential issues. One way to do this is by recursively converting nested objects to arrays. This ensures that all nested objects are properly converted and included in the final array representation.

function objectToArray($object) {
    if (is_object($object)) {
        $object = get_object_vars($object);
    }
    
    if (is_array($object)) {
        return array_map('objectToArray', $object);
    } else {
        return $object;
    }
}

// Example usage
$nestedObject = new stdClass();
$nestedObject->nestedProperty = 'value';

$object = new stdClass();
$object->property1 = 'value1';
$object->property2 = $nestedObject;

$array = objectToArray($object);
print_r($array);