Convert a PHP object to an associative array

后端 未结 30 2255
走了就别回头了
走了就别回头了 2020-11-22 02:18

I\'m integrating an API to my website which works with data stored in objects while my code is written using arrays.

I\'d like a quick-and-dirty function to convert

30条回答
  •  面向向阳花
    2020-11-22 02:47

    Custom function to convert stdClass to an array:

    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;
        }
    }
    

    Another custom function to convert Array to stdClass:

    function arrayToObject($d) {
        if (is_array($d)) {
            /*
            * Return array converted to object
            * Using __FUNCTION__ (Magic constant)
            * for recursive call
            */
            return (object) array_map(__FUNCTION__, $d);
        } else {
            // Return object
            return $d;
        }
    }
    

    Usage Example:

    // Create new stdClass Object
    $init = new stdClass;
    
    // Add some test data
    $init->foo = "Test data";
    $init->bar = new stdClass;
    $init->bar->baaz = "Testing";
    $init->bar->fooz = new stdClass;
    $init->bar->fooz->baz = "Testing again";
    $init->foox = "Just test";
    
    // Convert array to object and then object back to array
    $array = objectToArray($init);
    $object = arrayToObject($array);
    
    // Print objects and array
    print_r($init);
    echo "\n";
    print_r($array);
    echo "\n";
    print_r($object);
    

提交回复
热议问题