복붙노트

PHP에서 배열을 객체로 변환하는 방법은 무엇입니까?

PHP

PHP에서 배열을 객체로 변환하는 방법은 무엇입니까?

이 배열을 객체로 변환하려면 어떻게해야합니까?

    [128] => Array
        (
            [status] => Figure A.
 Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution.
        )

    [129] => Array
        (
            [status] => The other day at work, I had some spare time
        )

)

해결법

  1. ==============================

    1.가장 단순한 경우 배열을 객체로 "캐스팅"하는 것만으로도 충분합니다.

    가장 단순한 경우 배열을 객체로 "캐스팅"하는 것만으로도 충분합니다.

    $object = (object) $array;
    

    또 다른 옵션은 표준 클래스를 변수로 인스턴스화하고 배열을 반복하면서 값을 다시 할당하는 것입니다.

    $object = new stdClass();
    foreach ($array as $key => $value)
    {
        $object->$key = $value;
    }
    

    Edson Medina가 지적한 것처럼 정말 깨끗한 해결책은 내장 된 json_ 함수를 사용하는 것입니다.

    $object = json_decode(json_encode($array), FALSE);
    

    또한 이것은 (재귀 적으로) 모든 하위 배열을 객체로 변환하며, 원하는지 여부는 다를 수 있습니다. 불행히도 루핑 방식에 비해 2-3 배의 성능을 발휘합니다.

    경고! (의견에 대한 울트라 덕분에) :

  2. ==============================

    2.당신은 간단하게 타입 변환을 사용하여 배열을 객체로 변환 할 수 있습니다.

    당신은 간단하게 타입 변환을 사용하여 배열을 객체로 변환 할 수 있습니다.

    // *convert array to object* Array([id]=> 321313[username]=>shahbaz)
    $object = (object) $array_name;
    
    //now it is converted to object and you can access it.
    echo $object->username;
    
  3. ==============================

    3.세 가지 방법이 있습니다.

    세 가지 방법이 있습니다.

  4. ==============================

    4.빠른 해킹 :

    빠른 해킹 :

    // assuming $var is a multidimensional array
    $obj = json_decode (json_encode ($var), FALSE);
    

    예쁘지 않지만 작동합니다.

  5. ==============================

    5.쉬운 방법이 될 것입니다.

    쉬운 방법이 될 것입니다.

    $object = (object)$array;
    

    그러나 그것은 당신이 원하는 것이 아닙니다. 객체를 원한다면 무언가를하고 싶지만이 질문에는 빠져 있습니다. 객체를 사용하는 이유만으로 객체를 사용하는 것은 의미가 없습니다.

  6. ==============================

    6.필요한 곳과 개체에 액세스하는 방법에 따라 여러 가지 방법이 있습니다.

    필요한 곳과 개체에 액세스하는 방법에 따라 여러 가지 방법이 있습니다.

    예를 들면 : 그냥 타입 변환합니다.

    $object =  (object) $yourArray;
    

    그러나 가장 호환이 잘되는 방법은 유형을 지정하는 문자열을 기반으로 표준 PHP 캐스팅을 구현하는 유틸리티 메서드 (PHP의 일부는 아님)를 사용하는 것입니다 (또는 값을 직접 참조 해제하지 않고 무시).

    /**
     * dereference a value and optionally setting its type
     *
     * @param mixed $mixed
     * @param null  $type (optional)
     *
     * @return mixed $mixed set as $type
     */
    function rettype($mixed, $type = NULL) {
        $type === NULL || settype($mixed, $type);
        return $mixed;
    }
    

    사례의 사용 예제 (온라인 데모) :

    $yourArray = Array('status' => 'Figure A. ...');
    
    echo rettype($yourArray, 'object')->status; // prints "Figure A. ..."
    
  7. ==============================

    7.이 방법은 간단합니다. 이렇게하면 재귀 적 배열에 대한 객체도 생성됩니다.

    이 방법은 간단합니다. 이렇게하면 재귀 적 배열에 대한 객체도 생성됩니다.

    $object = json_decode(json_encode((object) $yourArray), FALSE);
    
  8. ==============================

    8.이 하나는 나를 위해 일했다.

    이 하나는 나를 위해 일했다.

      function array_to_obj($array, &$obj)
      {
        foreach ($array as $key => $value)
        {
          if (is_array($value))
          {
          $obj->$key = new stdClass();
          array_to_obj($value, $obj->$key);
          }
          else
          {
            $obj->$key = $value;
          }
        }
      return $obj;
      }
    
    function arrayToObject($array)
    {
     $object= new stdClass();
     return array_to_obj($array,$object);
    }
    

    사용법 :

    $myobject = arrayToObject($array);
    print_r($myobject);
    

    반환 :

        [127] => stdClass Object
            (
                [status] => Have you ever created a really great looking website design
            )
    
        [128] => stdClass Object
            (
                [status] => Figure A.
     Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution.
            )
    
        [129] => stdClass Object
            (
                [status] => The other day at work, I had some spare time
            )
    

    평소처럼 루프를 반복 할 수 있습니다.

    foreach($myobject as $obj)
    {
      echo $obj->status;
    }
    
  9. ==============================

    9.필자가 알고있는 한 내장 메소드가 없지만 간단한 루프만큼 쉽습니다.

    필자가 알고있는 한 내장 메소드가 없지만 간단한 루프만큼 쉽습니다.

        $obj= new stdClass();
    
        foreach ($array as $k=> $v) {
            $obj->{$k} = $v;
        }
    

    재귀 적으로 객체를 빌드하는 데 필요한 경우이를 설명 할 수 있습니다.

  10. ==============================

    10.실제로 이것을 다차원 배열에 사용하려면 재귀를 사용하는 것이 좋습니다.

    실제로 이것을 다차원 배열에 사용하려면 재귀를 사용하는 것이 좋습니다.

    static public function array_to_object(array $array)
    {
        foreach($array as $key => $value)
        {
            if(is_array($value))
            {
                $array[$key] = self::array_to_object($value);
            }
        }
        return (object)$array;
    }
    
  11. ==============================

    11.나는 확실히 다음과 같이 깨끗한 방법으로 갈 것이다 :

    나는 확실히 다음과 같이 깨끗한 방법으로 갈 것이다 :

    <?php
    
    class Person {
    
      private $name;
      private $age;
      private $sexe;
    
      function __construct ($payload)
      {
         if (is_array($payload))
              $this->from_array($payload);
      }
    
    
      public function from_array($array)
      {
         foreach(get_object_vars($this) as $attrName => $attrValue)
            $this->{$attrName} = $array[$attrName];
      }
    
      public function say_hi ()
      {
         print "hi my name is {$this->name}";
      }
    }
    
    print_r($_POST);
    $mike = new Person($_POST);
    $mike->say_hi();
    
    ?>
    

    제출하는 경우 :

    당신은 이것을 얻을 것이다 :

    나는 더 논리적 인 것을 발견했다. 위의 해답을 객체의 용도로 사용해야한다 (캡슐화 된 귀여운 객체).

    또한 get_object_vars를 사용하면 조작 된 오브젝트에 추가 속성이 작성되지 않습니다 (성이있는 차나 4 개의 바퀴를 사용하는 사람은 원하지 않음).

  12. ==============================

    12.재귀는 당신의 친구입니다.

    재귀는 당신의 친구입니다.

    function __toObject(Array $arr) {
        $obj = new stdClass();
        foreach($arr as $key=>$val) {
            if (is_array($val)) {
                $val = __toObject($val);
            }
            $obj->$key = $val;
        }
    
        return $obj;
    }
    
  13. ==============================

    13.쉬운:

    쉬운:

    $object = json_decode(json_encode($array));
    

    예:

    $array = array(
        'key' => array(
            'k' => 'value',
        ),
        'group' => array('a', 'b', 'c')
    );
    
    $object = json_decode(json_encode($array));
    

    다음은 사실입니다.

    $object->key->k === 'value';
    $object->group === array('a', 'b', 'c')
    
  14. ==============================

    14.ArrayObject를 사용할 수도 있습니다. 예를 들면 다음과 같습니다 :

    ArrayObject를 사용할 수도 있습니다. 예를 들면 다음과 같습니다 :

    <?php
        $arr = array("test",
                     array("one"=>1,"two"=>2,"three"=>3), 
                     array("one"=>1,"two"=>2,"three"=>3)
               );
        $o = new ArrayObject($arr);
        echo $o->offsetGet(2)["two"],"\n";
        foreach ($o as $key=>$val){
            if (is_array($val)) {
                foreach($val as $k => $v) {
                   echo $k . ' => ' . $v,"\n";
                }
            }
            else
            {
                   echo $val,"\n";
            }
        }
    ?>
    
    //Output:
      2
      test
      one => 1
      two => 2
      three => 3
      one => 1
      two => 2
      three => 3
    
  15. ==============================

    15.내가 만든이 함수를 사용하십시오 :

    내가 만든이 함수를 사용하십시오 :

    function buildObject($class,$data){
        $object = new $class;
        foreach($data as $key=>$value){
            if(property_exists($class,$key)){
                $object->{'set'.ucfirst($key)}($value);
            }
        }
        return $object;
    }
    

    용법:

    $myObject = buildObject('MyClassName',$myArray);
    
  16. ==============================

    16.조금 복잡하지만 쉽게 확장 할 수있는 기술 :

    조금 복잡하지만 쉽게 확장 할 수있는 기술 :

    배열이 있다고 가정합니다.

    $a = [
    'name' => 'ankit',
    'age' => '33',
    'dob' => '1984-04-12'
    ];
    

    이 배열의 속성이 더 많거나 적은 person 클래스가 있다고 가정합니다. 예를 들면

    class Person 
    {
        private $name;
        private $dob;
        private $age;
        private $company;
        private $city;
    }
    

    여전히 배열을 person 객체로 변경하고 싶다면. ArrayIterator 클래스를 사용할 수 있습니다.

    $arrayIterator = new \ArrayIterator($a); // Pass your array in the argument.
    

    이제 당신은 iterator 객체를 가진다.

    FilterIterator 클래스를 확장 한 클래스를 작성하십시오. 여기서 추상 메소드 accept를 정의해야한다. 예제를 따른다.

    class PersonIterator extends \FilterIterator
    {
        public function accept()
        {
            return property_exits('Person', parent::current());
        }
    
    }
    

    위의 구현은 클래스에있는 경우에만 속성을 바인딩합니다.

    PersonIterator 클래스에 메서드를 한 개 더 추가합니다.

    public function getObject(Person $object)
    {
            foreach ($this as $key => $value)
            {
                $object->{'set' . underscoreToCamelCase($key)}($value);
            }
            return $object;
    }
    

    클래스에 mutator가 정의되어 있는지 확인하십시오. 이제 당신은 객체를 생성하고자하는 곳에서이 함수를 호출 할 준비가되었습니다.

    $arrayiterator = new \ArrayIterator($a);
    $personIterator = new \PersonIterator($arrayiterator);
    
    $personIterator->getObject(); // this will return your Person Object. 
    
  17. ==============================

    17.또한 변수 왼쪽에 (object)를 추가하여 새 객체를 만들 수도 있습니다.

    또한 변수 왼쪽에 (object)를 추가하여 새 객체를 만들 수도 있습니다.

    <?php
    $a = Array
        ( 'status' => " text" );
    var_dump($a);
    $b = (object)$a;
    var_dump($b);
    var_dump($b->status);
    

    http://codepad.org/9YmD1KsU

  18. ==============================

    18.json_encode를 사용하는 것은 비 UTF-8 데이터를 처리하는 방식 때문에 문제가 있습니다. json_encode / json_encode 메소드가 비 연관 배열을 배열로 남겨 둡니다. 이것은 당신이 원하는 것일 수도 아닐 수도 있습니다. 최근 json_ 함수를 사용하지 않고이 솔루션의 기능을 다시 만들 필요가있는 위치에있었습니다. 다음은 내가 생각해 낸 것입니다.

    json_encode를 사용하는 것은 비 UTF-8 데이터를 처리하는 방식 때문에 문제가 있습니다. json_encode / json_encode 메소드가 비 연관 배열을 배열로 남겨 둡니다. 이것은 당신이 원하는 것일 수도 아닐 수도 있습니다. 최근 json_ 함수를 사용하지 않고이 솔루션의 기능을 다시 만들 필요가있는 위치에있었습니다. 다음은 내가 생각해 낸 것입니다.

    /**
     * Returns true if the array has only integer keys
     */
    function isArrayAssociative(array $array) {
        return (bool)count(array_filter(array_keys($array), 'is_string'));
    }
    
    /**
     * Converts an array to an object, but leaves non-associative arrays as arrays. 
     * This is the same logic that `json_decode(json_encode($arr), false)` uses.
     */
    function arrayToObject(array $array, $maxDepth = 10) {
        if($maxDepth == 0) {
            return $array;
        }
    
        if(isArrayAssociative($array)) {
            $newObject = new \stdClass;
            foreach ($array as $key => $value) {
                if(is_array($value)) {
                    $newObject->{$key} = arrayToObject($value, $maxDepth - 1);
                } else {
                    $newObject->{$key} = $value;
                }
            }
            return $newObject;
        } else {
    
            $newArray = array();
            foreach ($array as $value) {
                if(is_array($value)) {
                    $newArray[] = arrayToObject($value, $maxDepth - 1);
                } else {
                    $newArray[] = $value;
                }                
            }
            return $newArray;
        }
    }
    
  19. ==============================

    19.세계에서 가장 좋은 방법 :)

    세계에서 가장 좋은 방법 :)

    function arrayToObject($conArray)
    {
        if(is_array($conArray)){
            /*
            * Return array converted to object
            * Using __FUNCTION__ (Magic constant)
            * for recursive call
            */
            return (object) array_map(__FUNCTION__, $conArray);
        }else{
            // Return object
            return $conArray;
        }
    }
    

    다른 방법을 사용하면 문제가 발생합니다. 이것이 가장 좋은 방법입니다. 너는 이제까지 보았다.

  20. ==============================

    20.짧막 한 농담

    짧막 한 농담

    $object= json_decode(json_encode($result_array, JSON_FORCE_OBJECT));
    
  21. ==============================

    21.필자는 람다 함수를 사용하여 main 함수 내에서 'innerfunc'를 잠그기 때문에 PHP7이 필요합니다. 람다 함수는 재귀 적으로 호출되므로 "use (& $ innerfunc)"가 필요합니다. 당신은 PHP5에서 할 수 있지만 innerfunc를 숨길 수는 없습니다.

    필자는 람다 함수를 사용하여 main 함수 내에서 'innerfunc'를 잠그기 때문에 PHP7이 필요합니다. 람다 함수는 재귀 적으로 호출되므로 "use (& $ innerfunc)"가 필요합니다. 당신은 PHP5에서 할 수 있지만 innerfunc를 숨길 수는 없습니다.

    function convertArray2Object($defs) {
        $innerfunc = function ($a) use ( &$innerfunc ) {
           return (is_array($a)) ? (object) array_map($innerfunc, $a) : $a; 
        };
        return (object) array_map($innerfunc, $defs);
    }
    
  22. ==============================

    22.분명히 다른 사람들의 해답을 외삽 한 것입니다.하지만 여기에 멀치 차원 배열을 객체로 변환하는 재귀 함수가 있습니다.

    분명히 다른 사람들의 해답을 외삽 한 것입니다.하지만 여기에 멀치 차원 배열을 객체로 변환하는 재귀 함수가 있습니다.

       function convert_array_to_object($array){
          $obj= new stdClass();
          foreach ($array as $k=> $v) {
             if (is_array($v)){
                $v = convert_array_to_object($v);   
             }
             $obj->{strtolower($k)} = $v;
          }
          return $obj;
       }
    

    배열에 숫자 키가있는 경우 {}를 사용하여 결과 객체에서 참조 할 수 있습니다 (예 : $ obj-> prop -> {4} -> prop)

  23. ==============================

    23.이 모든 코드에서 영감을 받아 특정 클래스 이름, 생성자 메서드, 'beans'패턴 및 strict 모드 (기존 속성 만 설정)를 피할 수있는 향상된 버전을 만들려고했습니다.

    이 모든 코드에서 영감을 받아 특정 클래스 이름, 생성자 메서드, 'beans'패턴 및 strict 모드 (기존 속성 만 설정)를 피할 수있는 향상된 버전을 만들려고했습니다.

        class Util {
    
    static function arrayToObject($array, $class = 'stdClass', $strict = false) {
            if (!is_array($array)) {
                return $array;
            }
    
            //create an instance of an class without calling class's constructor
            $object = unserialize(
                    sprintf(
                            'O:%d:"%s":0:{}', strlen($class), $class
                    )
            );
    
            if (is_array($array) && count($array) > 0) {
                foreach ($array as $name => $value) {
                    $name = strtolower(trim($name));
                    if (!empty($name)) {
    
                        if(method_exists($object, 'set'.$name)){
                            $object->{'set'.$name}(Util::arrayToObject($value));
                        }else{
                            if(($strict)){
    
                                if(property_exists($class, $name)){
    
                                    $object->$name = Util::arrayToObject($value); 
    
                                }
    
                            }else{
                                $object->$name = Util::arrayToObject($value); 
                            }
    
                        }
    
                    }
                }
                return $object;
            } else {
                return FALSE;
            }
            }
    }
    
  24. ==============================

    24.이 함수는 json_decode (json_encode ($ arr), false)와 동일하게 작동합니다.

    이 함수는 json_decode (json_encode ($ arr), false)와 동일하게 작동합니다.

    function arrayToObject(array $arr)
    {
        $flat = array_keys($arr) === range(0, count($arr) - 1);
        $out = $flat ? [] : new \stdClass();
    
        foreach ($arr as $key => $value) {
            $temp = is_array($value) ? $this->arrayToObject($value) : $value;
    
            if ($flat) {
                $out[] = $temp;
            } else {
                $out->{$key} = $temp;
            }
        }
    
        return $out;
    }
    
    $arr = ["a", "b", "c"];
    var_export(json_decode(json_encode($arr)));
    var_export($this->arrayToObject($arr));
    

    산출:

    array(
        0 => 'a',
        1 => 'b',
        2 => 'c',
    )
    array(
        0 => 'a',
        1 => 'b',
        2 => 'c',
    )
    
    $arr = [["a" => 1], ["a" => 1], ["a" => 1]];
    var_export(json_decode(json_encode($arr)));
    var_export($this->arrayToObject($arr));
    

    산출:

    array(
        0 => stdClass::__set_state(array('a' => 1,)),
        1 => stdClass::__set_state(array('a' => 1,)),
        2 => stdClass::__set_state(array('a' => 1,)),
    )
    array(
        0 => stdClass::__set_state(array('a' => 1,)),
        1 => stdClass::__set_state(array('a' => 1,)),
        2 => stdClass::__set_state(array('a' => 1,)),
    )
    
    $arr = ["a" => 1];
    var_export(json_decode($arr));
    var_export($this->arrayToObject($arr));
    

    산출:

    stdClass::__set_state(array('a' => 1,))
    stdClass::__set_state(array('a' => 1,))
    
  25. ==============================

    25.내가 사용하는 것 (그것은 반원이다) :

    내가 사용하는 것 (그것은 반원이다) :

    const MAX_LEVEL = 5; // change it as needed
    
    public function arrayToObject($a, $level=0)
    {
    
        if(!is_array($a)) {
            throw new InvalidArgumentException(sprintf('Type %s cannot be cast, array expected', gettype($a)));
        }
    
        if($level > self::MAX_LEVEL) {
            throw new OverflowException(sprintf('%s stack overflow: %d exceeds max recursion level', __METHOD__, $level));
        }
    
        $o = new stdClass();
        foreach($a as $key => $value) {
            if(is_array($value)) { // convert value recursively
                $value = $this->arrayToObject($value, $level+1);
            }
            $o->{$key} = $value;
        }
        return $o;
    }
    
  26. ==============================

    26.CakePHP는 기본적으로 배열을 객체에 매핑하는 재귀 적 Set :: map 클래스를 가지고 있습니다. 객체를 원하는 모양으로 보이게하려면 배열의 모양을 변경해야 할 수도 있습니다.

    CakePHP는 기본적으로 배열을 객체에 매핑하는 재귀 적 Set :: map 클래스를 가지고 있습니다. 객체를 원하는 모양으로 보이게하려면 배열의 모양을 변경해야 할 수도 있습니다.

    http://api.cakephp.org/view_source/set/#line-158

    최악의 경우,이 기능으로 몇 가지 아이디어를 얻을 수 있습니다.

  27. ==============================

    27.나는 아주 간단한 방법으로 해냈다.

    나는 아주 간단한 방법으로 해냈다.

        $list_years         = array();
        $object             = new stdClass();
    
        $object->year_id   = 1 ;
        $object->year_name = 2001 ;
        $list_years[]       = $object;
    
  28. ==============================

    28.

    function object_to_array($data)
    {
        if (is_array($data) || is_object($data))
        {
            $result = array();
            foreach ($data as $key => $value)
            {
                $result[$key] = object_to_array($value);
            }
            return $result;
        }
        return $data;
    }
    
    function array_to_object($data)
    {
        if (is_array($data) || is_object($data))
        {
            $result= new stdClass();
            foreach ($data as $key => $value)
            {
                $result->$key = array_to_object($value);
            }
            return $result;
        }
        return $data;
    }
    
  29. ==============================

    29.접두사로 (array)와 (object)를 사용하면 객체 배열을 표준 배열과 vice-verse로 간단히 변환 할 수 있습니다.

    접두사로 (array)와 (object)를 사용하면 객체 배열을 표준 배열과 vice-verse로 간단히 변환 할 수 있습니다.

    <?php
    //defining an array
    $a = array('a'=>'1','b'=>'2','c'=>'3','d'=>'4');
    
    //defining an object array
    $obj = new stdClass();
    $obj->a = '1';
    $obj->b = '2';
    $obj->c = '3';
    $obj->d = '4';
    
    print_r($a);echo '<br>';
    print_r($obj);echo '<br>';
    
    //converting object array to array
    $b = (array) $obj;
    print_r($b);echo '<br>';
    
    //converting array to object
    $c = (object) $a;
    print_r($c);echo '<br>';
    ?>
    
  30. ==============================

    30.Yaml 파일 연관 배열을 객체 상태로 파싱하려면 다음을 사용합니다.

    Yaml 파일 연관 배열을 객체 상태로 파싱하려면 다음을 사용합니다.

    객체가 숨겨져있는 경우 제공된 모든 배열을 검사하고 객체에서도 해당 배열을 검사합니다.

        /**
         * Makes a config object from an array, making the first level keys properties a new object.
         * Property values are converted to camelCase and are not set if one already exists.
         * @param array $configArray Config array.
         * @param boolean $strict To return an empty object if $configArray is not an array
         * @return stdObject The config object
         */
        public function makeConfigFromArray($configArray = [],$strict = true)
        {
            $object = new stdClass();
    
            if (!is_array($configArray)) {
                if(!$strict && !is_null($configArray)) {
                    return $configArray;
                }
                return $object;
            }
    
            foreach ($configArray as $name => $value) {
                $_name = camel_case($name);
                if(is_array($value)) {
                    $makeobject = true;
                    foreach($value as $key => $val) {
                        if(is_numeric(substr($key,0,1))) {
                            $makeobject = false;
                        }
                        if(is_array($val)) {
                            $value[$key] = $this->makeConfigFromArray($val,false);
                        }
                    }
                    if($makeobject) {
                        $object->{$name} = $object->{$_name} = $this->makeConfigFromArray($value,false);
                    }
                    else {
                        $object->{$name} = $object->{$_name} = $value;
                    }
    
                }
                else {
                    $object->{$name} = $object->{$_name} = $value;
                }
            }
    
            return $object;
        }
    

    이것은 yaml을 다음과 같이 설정합니다.

    fields:
        abc:
            type: formfield
            something:
                - a
                - b
                - c
                - d:
                    foo: 
                       bar
    

    배열로 구성 :

    array:1 [
      "fields" => array:1 [
        "abc" => array:2 [
          "type" => "formfield"
          "something" => array:4 [
            0 => "a"
            1 => "b"
            2 => "c"
            3 => array:1 [
              "d" => array:1 [
                "foo" => "bar"
              ]
            ]
          ]
        ]
      ]
    ]
    

    의 대상으로 :

    {#325
      +"fields": {#326
        +"abc": {#324
          +"type": "formfield"
          +"something": array:4 [
            0 => "a"
            1 => "b"
            2 => "c"
            3 => {#328
              +"d": {#327
                +"foo": "bar"
              }
            }
          ]
        }
      }
    }
    
  31. from https://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php by cc-by-sa and MIT license