PHP - recursive Array to Object?

前端 未结 14 1221
夕颜
夕颜 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 15:11

    You can use the array_map recursively:

    public static function _arrayToObject($array) {
        return is_array($array) ? (object) array_map([__CLASS__, __METHOD__], $array) : $array;
    }
    

    Works perfect for me since it doesn't cast for example Carbon objects to a basic stdClass (which the json encode/decode does)

    0 讨论(0)
  • 2020-12-14 15:13

    EDIT: This function is conversion from object to array.

    From https://forrst.com/posts/PHP_Recursive_Object_to_Array_good_for_handling-0ka

    protected function object_to_array($obj)
    {
        $arrObj = is_object($obj) ? get_object_vars($obj) : $obj;
        foreach ($arrObj as $key => $val) {
                $val = (is_array($val) || is_object($val)) ? $this->object_to_array($val) : $val;
                $arr[$key] = $val;
        }
        return $arr;
    }
    
    0 讨论(0)
提交回复
热议问题