PHP - recursive Array to Object?

前端 未结 14 1266
夕颜
夕颜 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条回答
  •  -上瘾入骨i
    2020-12-14 14:56

    Here is a smooth way to do it that can handle an associative array with great depth and doesn't overwrite object properties that are not in the array.

         $v )
            {
                if ( is_array( $v ) )
                {
                    $o->{$k} = setPropsViaArray( $v, ! empty ( $o->{$k} ) ? $o->{$k} : new stdClass() );
                }
                else
                {
                    $o->{$k} = $v;
                }
            }
            return $o;
        };
    
        setPropsViaArray( $newArrayData, $existingObject );
    

提交回复
热议问题