PHP - recursive Array to Object?

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

    As far as I can tell, there is no prebuilt solution for this, so you can just roll your own:

    function array_to_object($array) {
      $obj = new stdClass;
      foreach($array as $k => $v) {
         if(strlen($k)) {
            if(is_array($v)) {
               $obj->{$k} = array_to_object($v); //RECURSION
            } else {
               $obj->{$k} = $v;
            }
         }
      }
      return $obj;
    } 
    

提交回复
热议问题