source

PHP에서 어레이를 개체로 변환하는 방법

manysource 2022. 10. 14. 22:11

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"
    )

가장 간단한 경우에는 어레이를 개체로 "캐스팅"하는 것으로 충분합니다.

$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배 향상되었습니다.

경고! (Ultra의 코멘트 덕분)

다른 환경의 json_decode는 다양한 방법으로 UTF-8 데이터를 변환합니다.결국 현지에서는 '240.00'이라는 값과 생산에서는 '240'이라는 값을 얻게 됩니다. - 대규모 재앙이죠.변환에 실패한 문자열이 NULL로 반환되는 경우 Morover

유형 캐스팅을 사용하여 배열을 개체로 변환할 수 있습니다.

// *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;

쉬운 방법은

$object = (object)$array;

하지만 네가 원하는 건 그게 아니야무언가를 달성하고 싶은 대상이 있다면, 이 질문에는 그것이 빠져 있습니다.오브젝트를 사용한다는 이유만으로 오브젝트를 사용하는 것은 의미가 없습니다.

빠른 해킹:

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

예쁘진 않지만 효과가 있어.

다음은 세 가지 방법입니다.

  1. 실제 객체 위조:

    class convert
    {
        public $varible;
    
        public function __construct($array)
        {
            $this = $array;
        }
    
        public static function toObject($array)
        {
            $array = new convert($array);
            return $array;
        }
    }
    
  2. 배열을 객체에 캐스팅하여 객체로 변환합니다.

    $array = array(
        // ...
    );
    $object = (object) $array;
    
  3. 어레이를 수동으로 개체로 변환합니다.

    $object = object;
    foreach ($arr as $key => $value) {
        $object->{$key} = $value;
    }
    

단순하게 하기 위해 재귀 배열에 대한 개체도 만듭니다.

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

필요한 위치와 개체에 액세스하는 방법에 따라 다양한 방법이 있습니다.

예를 들어, 타이프캐스트만 하면 됩니다.

$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. ..."

(개체) 함수를 사용하여 배열을 개체로 변환할 수 있습니다.

$arr= [128=> ['status'=>
                 'Figure A. Facebook \'s horizontal scrollbars showing up on a 1024x768 screen resolution.'],
                  129=>['status'=>'The other day at work, I had some spare time']];

            $ArrToObject=(object)$arr;
            var_dump($ArrToObject);

결과는 어레이를 포함하는 개체입니다.

object(stdClass) #1048 (2) { [128]=> array (1) {

["status"]=> string(87) "그림 A.1024 x 768 화면 해상도에 표시되는 페이스북 가로 스크롤바." }

[http] = > array (1) {["status"] = > string (44) "일전에 회사에서 시간이 좀 있었어요" } }

이건 나한테 효과가 있었어

  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;
}

저도 이 문제가 있었습니다만, json_decode가 JSON 어레이를 오브젝트로 변환하고 있는 것을 알 수 있었습니다.

그래서 오브젝트의 JSON 문자열을 반환하는 json_encode($PHPArray)를 사용하여 해결 방법을 찾아냈고, 그 문자열을 Json_decode($string)로 디코딩하면 완벽하게 구조화된 오브젝트가 반환됩니다.속기

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

또는

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

제가 아는 한 이 작업을 수행하는 기본 제공 방법은 없지만 간단한 루프만큼 쉽습니다.

    $obj= new stdClass();

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

오브젝트를 재귀적으로 빌드하기 위해서 필요한 경우는, 이것에 대해 설명할 수 있습니다.

실제로 다차원 배열에서 이 기능을 사용하려면 재귀 기능을 사용해야 합니다.

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;
}

나는 분명히 이렇게 깨끗한 길을 갈 것이다.

<?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륜을 사용하는 사람은 원하지 않습니다).

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

어레이가 있다고 가정합니다.

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

이 배열의 속성이 많거나 적을 수 있는 개인 클래스가 있다고 가정합니다.예를들면

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

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

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

이제 반복기 개체가 있습니다.

FilterIterator 클래스를 확장하는 클래스를 만듭니다. 여기서 추상 메서드 수용을 정의해야 합니다.예에 따르다

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

위의 임플리케이션은 클래스에 속성이 존재하는 경우에만 속성을 바인딩합니다.

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

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

클래스에 정의된 돌연변이가 있는지 확인하십시오.이것으로 오브젝트를 작성할 함수를 호출할 수 있습니다.

$arrayiterator = new \ArrayIterator($a);
$personIterator = new \PersonIterator($arrayiterator);

$personIterator->getObject(); // this will return your Person Object. 

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

사용하고 있는 것(클래스 멤버):

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;
}

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

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

    return $obj;
}

메인 함수 내의 '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);
}

내가 만든 이 기능을 사용합니다.

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);

라이너 1대

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

간단:

$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')

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

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

http://codepad.org/9YmD1KsU

세계 최고의 방법:)

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;
    }
}

만약 당신이 다른 방법을 사용한다면 당신은 문제가 생길 것이다.이것이 가장 좋은 방법입니다.너도 본 적 있을 거야

사용.json_encode는 UTF-8 이외의 데이터를 처리하는 방법 때문에 문제가 있습니다.주목할 필요가 있습니다.json_encode/json_encode또한 method는 비관련 어레이를 어레이로 남깁니다.이것은 당신이 원하는 것일 수도 있고 아닐 수도 있습니다.저는 최근에 이 솔루션의 기능을 재작성할 필요가 있었지만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;
    }
}

분명히 다른 사람의 답변을 추측해 낸 것일 뿐이지만, 여기 멀티차원 배열을 객체로 변환하는 재귀 함수가 있습니다.

   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)

오브젝트로의 다차원 배열.Bing 검색 API try and catch 메서드의 변환에 사용됩니다.

try {
        // Perform the Web request and get the JSON response
        $context = stream_context_create($options);
        $results = file_get_contents($url . "?cc=" . $country . "&category=" . $type, false, $context);
        $results = json_decode($results);
        return response()->json($results);
    } catch (\Exception $e) {
        $results = array('value' => array(
                (object) array(
                    "name" => "Unable to Retrive News",
                    "url" => "http://www.sample.com/",
                    "image" => (object) array("thumbnail" => (object) array("contentUrl" => "")),
                    "publishedAt" => "",
                    "description" => "")
            )
        );
        $results = (object) $results;
        return response()->json($results);
    }

Reflection을 사용할 수 있습니다.

<?php

$array = ['name'=>'maria','age'=>33];

class Person {

    public $name;
    public $age;

    public function __construct(string $name, string $age){
        $this->name  = $name;
        $this->age = $age;
    }
}

function arrayToObject(array $array, string $class_name){

    $r = new ReflectionClass($class_name);
    $object = $r->newInstanceWithoutConstructor();
    $list = $r->getProperties();
    foreach($list as $prop){
      $prop->setAccessible(true);
      if(isset($array[$prop->name]))
        $prop->setValue($object, $array[$prop->name]);
    } 

    return $object;

}

$pessoa1 = arrayToObject($array, 'Person');
var_dump($pessoa1);

CakePHP에는 기본적으로 배열을 객체에 매핑하는 재귀 Set:: 맵 클래스가 있습니다.개체를 원하는 대로 표시하기 위해 배열 모양을 변경해야 할 수 있습니다.

http://api.cakephp.org/view_source/set/ #회선표시

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

이러한 모든 코드에서 영감을 얻어 특정 클래스 이름, 생성자 메서드 회피, '빈' 패턴 및 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;
        }
        }
}

코드

이 함수는 다음과 같이 동작합니다.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;
}

테스트

테스트 1: 플랫 어레이

$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',
)

테스트 2: 객체 배열

$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,)),
)

테스트 3: 객체

$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,))

언급URL : https://stackoverflow.com/questions/1869091/how-to-convert-an-array-to-object-in-php