PHP - recursive Array to Object?

前端 未结 14 1218
夕颜
夕颜 2020-12-14 14:10

Is there a way to convert a multidimensional array to a stdClass object in PHP?

Casting as (object) doesn\'t seem to work recu

14条回答
  •  醉梦人生
    2020-12-14 14:50

    I know this answer is coming late but I'll post it for anyone who's looking for a solution.

    Instead of all this looping etc, you can use PHP's native json_* function. I've got a couple of handy functions that I use a lot

    /**
     * Convert an array into a stdClass()
     * 
     * @param   array   $array  The array we want to convert
     * 
     * @return  object
     */
    function arrayToObject($array)
    {
        // First we convert the array to a json string
        $json = json_encode($array);
    
        // The we convert the json string to a stdClass()
        $object = json_decode($json);
    
        return $object;
    }
    
    
    /**
     * Convert a object to an array
     * 
     * @param   object  $object The object we want to convert
     * 
     * @return  array
     */
    function objectToArray($object)
    {
        // First we convert the object into a json string
        $json = json_encode($object);
    
        // Then we convert the json string to an array
        $array = json_decode($json, true);
    
        return $array;
    }
    

    Hope this can be helpful

提交回复
热议问题