PHP - recursive Array to Object?

前端 未结 14 1283
夕颜
夕颜 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:47

    Here's a function to do an in-place deep array-to-object conversion that uses PHP internal (shallow) array-to-object type casting mechanism. It creates new objects only when necessary, minimizing data duplication.

    function toObject($array) {
        foreach ($array as $key=>$value)
            if (is_array($value))
                $array[$key] = toObject($value);
        return (object)$array;
    }
    

    Warning - do not use this code if there is a risk of having circular references.

提交回复
热议问题