programing

PHP의 객체에 json_encode 사용 (범위에 관계없이)

nasanasas 2020. 10. 28. 08:10
반응형

PHP의 객체에 json_encode 사용 (범위에 관계없이)


객체 목록을 json으로 출력하려고하는데 객체를 사용할 수있게 만드는 방법이 있는지 알고 싶습니다 json_encode. 내가 가진 코드는 다음과 같습니다.

$related = $user->getRelatedUsers();
echo json_encode($related);

지금은 사용자 배열을 반복하고 개별적으로 배열로 내보내 json_encode사용 가능한 json으로 전환하고 있습니다. 나는 이미 개체를 반복 가능하게 만들려고 시도했지만 json_encode어쨌든 건너 ​​뛰는 것 같습니다.

편집 : 여기에 var_dump ();

php > var_dump($a);
object(RedBean_OODBBean)#14 (2) {
  ["properties":"RedBean_OODBBean":private]=>
  array(11) {
    ["id"]=>
    string(5) "17972"
    ["pk_UniversalID"]=>
    string(5) "18830"
    ["UniversalIdentity"]=>
    string(1) "1"
    ["UniversalUserName"]=>
    string(9) "showforce"
    ["UniversalPassword"]=>
    string(32) ""
    ["UniversalDomain"]=>
    string(1) "0"
    ["UniversalCrunchBase"]=>
    string(1) "0"
    ["isApproved"]=>
    string(1) "0"
    ["accountHash"]=>
    string(32) ""
    ["CurrentEvent"]=>
    string(4) "1204"
    ["userType"]=>
    string(7) "company"
  }
  ["__info":"RedBean_OODBBean":private]=>
  array(4) {
    ["type"]=>
    string(4) "user"
    ["sys"]=>
    array(1) {
      ["idfield"]=>
      string(2) "id"
    }
    ["tainted"]=>
    bool(false)
    ["model"]=>
    object(Model_User)#16 (1) {
      ["bean":protected]=>
      *RECURSION*
    }
  }
}

그리고 다음은 json_encode가 제공하는 것입니다.

php > echo json_encode($a);
{}

나는 이것으로 끝났다.

    function json_encode_objs($item){   
        if(!is_array($item) && !is_object($item)){   
            return json_encode($item);   
        }else{   
            $pieces = array();   
            foreach($item as $k=>$v){   
                $pieces[] = "\"$k\":".json_encode_objs($v);   
            }   
            return '{'.implode(',',$pieces).'}';   
        }   
    }   

해당 객체로 가득 찬 배열 또는 단일 인스턴스를 사용하여 json으로 변환합니다. json_encode 대신 사용합니다. 더 나아질 수있는 곳이 있다고 확신하지만 json_encode가 노출 된 인터페이스를 기반으로 객체를 반복 할시기를 감지 할 수 있기를 바랐습니다.


RedBeanPHP 2.0에는 전체 빈 컬렉션을 배열로 변환하는 대량 내보내기 기능이 있습니다. 이것은 JSON 인코더와 함께 작동합니다 ..

json_encode( R::exportAll( $beans ) );

개체의 모든 속성은 비공개입니다. 일명 ... 클래스 범위 밖에서는 사용할 수 없습니다.

PHP <5.4 용 솔루션

개인 및 보호 개체 속성을 직렬화 하려면 이러한 목적으로 만든 데이터 구조를 활용 하는 JSON 인코딩 함수 클래스 내부 에 구현해야합니다 json_encode().

class Thing {
    ...
    public function to_json() {
        return json_encode(array(
            'something' => $this->something,
            'protected_something' => $this->get_protected_something(),
            'private_something' => $this->get_private_something()                
        ));
    }
    ...
}

PHP> = 5.4 용 솔루션

JsonSerializable인터페이스를 사용하여 사용자가 사용할 고유 한 json 표현을 제공하십시오.json_encode

class Thing implements JsonSerializable {
    ...
    public function jsonSerialize() {
        return [
            'something' => $this->something,
            'protected_something' => $this->get_protected_something(),
            'private_something' => $this->get_private_something()
        ];
    }
    ...
}

더 자세한 글


PHP> = 5.4.0에는 객체를 JSON으로 직렬화하는 새로운 인터페이스가 있습니다. JsonSerializable

객체에 인터페이스를 구현하고 JsonSerializable사용할 때 호출 될 메서드를 정의하기 만하면 됩니다 json_encode.

따라서 PHP> = 5.4.0 솔루션 은 다음과 같습니다.

class JsonObject implements JsonSerializable
{
    // properties

    // function called when encoded with json_encode
    public function jsonSerialize()
    {
        return get_object_vars($this);
    }
}

다음 코드는 나를 위해 일했습니다.

public function jsonSerialize()
{
    return get_object_vars($this);
}

나는 이것을 아직 언급하지 않았지만 bean에는이라는 내장 메서드가 getProperties()있습니다.

따라서 사용하려면 :

// What bean do we want to get?
$type = 'book';
$id = 13;

// Load the bean
$post = R::load($type,$id);

// Get the properties
$props = $post->getProperties();

// Print the JSON-encoded value
print json_encode($props);

결과는 다음과 같습니다.

{
    "id": "13",
    "title": "Oliver Twist",
    "author": "Charles Dickens"
}

이제 한 단계 더 나아가십시오. 콩 배열이 있다면 ...

// An array of beans (just an example)
$series = array($post,$post,$post);

... 다음을 수행 할 수 있습니다.

  • 루프를 사용하여 배열을 foreach반복합니다.

  • 각 요소 (빈)를 빈 속성 배열로 바꿉니다.

So this...

foreach ($series as &$val) {
  $val = $val->getProperties();
}

print json_encode($series);

...outputs this:

[
    {
        "id": "13",
        "title": "Oliver Twist",
        "author": "Charles Dickens"
    },
    {
        "id": "13",
        "title": "Oliver Twist",
        "author": "Charles Dickens"
    },
    {
        "id": "13",
        "title": "Oliver Twist",
        "author": "Charles Dickens"
    }
]

Hope this helps!


I usually include a small function in my objects which allows me to dump to array or json or xml. Something like:

public function exportObj($method = 'a')
{
     if($method == 'j')
     {
         return json_encode(get_object_vars($this));
     }
     else
     {
         return get_object_vars($this);
     }
}

either way, get_object_vars() is probably useful to you.


$products=R::findAll('products');
$string = rtrim(implode(',', $products), ',');
echo $string;

Here is my way:

function xml2array($xml_data)
{
    $xml_to_array = [];

    if(isset($xml_data))
    {
        if(is_iterable($xml_data))
        {
            foreach($xml_data as $key => $value)
            {
                if(is_object($value))
                {
                    if(empty((array)$value))
                    {
                        $value = (string)$value;
                    }
                    else
                    {
                        $value = (array)$value;
                    }
                    $value = xml2array($value);
                }
                $xml_to_array[$key] = $value;
            }
        }
        else
        {
            $xml_to_array = $xml_data;
        }
    }

    return $xml_to_array;
}

for an array of objects, I used something like this, while following the custom method for php < 5.4:

$jsArray=array();

//transaction is an array of the class transaction
//which implements the method to_json

foreach($transactions as $tran)
{
    $jsArray[]=$tran->to_json();
}

echo json_encode($jsArray);

참고URL : https://stackoverflow.com/questions/4697656/using-json-encode-on-objects-in-php-regardless-of-scope

반응형