PHP - recursive Array to Object?

前端 未结 14 1220
夕颜
夕颜 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.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-14 14:51
    /**
     * Recursively converts associative arrays to stdClass while keeping integer keys subarrays as arrays
     * (lists of scalar values or collection of objects).
     */
    function a2o( array $array ) {
        $resultObj = new \stdClass;
        $resultArr = array();
        $hasIntKeys = false;
        $hasStrKeys = false;
        foreach ( $array as $k => $v ) {
            if ( !$hasIntKeys ) {
                $hasIntKeys = is_int( $k );
            }
            if ( !$hasStrKeys ) {
                $hasStrKeys = is_string( $k );
            }
            if ( $hasIntKeys && $hasStrKeys ) {
                $e = new \Exception( 'Current level has both integer and string keys, thus it is impossible to keep array or convert to object' );
                $e->vars = array( 'level' => $array );
                throw $e;
            }
            if ( $hasStrKeys ) {
                $resultObj->{$k} = is_array( $v ) ? a2o( $v ) : $v;
            } else {
                $resultArr[$k] = is_array( $v ) ? a2o( $v ) : $v;
            }
        }
        return ($hasStrKeys) ? $resultObj : $resultArr;
    } 
    
    0 讨论(0)
  • 2020-12-14 14:51

    The shortest I could come up with:

    array_walk_recursive($obj, function (&$val) { if (is_object($val)) $val = get_object_vars($val); });
    
    0 讨论(0)
  • 2020-12-14 14:53

    The simpliest way to convert an associative array to object is:

    First encode it in json, then decode it.

    like $objectArray = json_decode(json_encode($associtiveArray));

    0 讨论(0)
  • 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;
    } 
    
    0 讨论(0)
提交回复
热议问题