PHP 오브젝트에서 json_encode 사용(범위에 관계없이)
를 json으로 사용할 수 .json_encode
내가 가지고 있는 암호는
$related = $user->getRelatedUsers();
echo json_encode($related);
json_encode
'json'은 'json'으로 하겠습니다.이미 반복할 수 있도록 해봤지만json_encode
어쨌든 그냥 건너뛰는 것 같아요
edit: var_var()입니다.
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_backs는 다음과 같이 말합니다.
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가, 노출된 인터페이스에 근거해 오브젝트를 통해서 반복하는 타이밍을 검출할 수 있으면 좋겠다고 생각하고 있었습니다.
당신의 물건의 모든 소유물은 비공개입니다. 일명...클래스 범위 밖에서는 사용할 수 없습니다.
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
개인 및 보호된 오브젝트 속성을 시리얼화하려면 클래스 내에서 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.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);
}
}
RedBeanPHP 2.0에는 전체 콩 컬렉션을 배열로 변환하는 대량 내보내기 기능이 있습니다.이것은 JSON 인코더로 동작합니다.
json_encode( R::exportAll( $beans ) );
다음 코드가 유효했습니다.
public function jsonSerialize()
{
return get_object_vars($this);
}
아직 못 봤는데 원두에는 원두라는 방법이 있어요.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
loopsyslog.syslog..syslog.각 요소(콩)를 콩의 특성 배열로 바꾸세요.
그래서 이게...
foreach ($series as &$val) {
$val = $val->getProperties();
}
print json_encode($series);
...이것을 확인합니다.
[
{
"id": "13",
"title": "Oliver Twist",
"author": "Charles Dickens"
},
{
"id": "13",
"title": "Oliver Twist",
"author": "Charles Dickens"
},
{
"id": "13",
"title": "Oliver Twist",
"author": "Charles Dickens"
}
]
이게 도움이 됐으면 좋겠네요!
보통 오브젝트에는 어레이, json 또는 xml로 덤프할 수 있는 작은 함수가 포함되어 있습니다.예를 들어 다음과 같습니다.
public function exportObj($method = 'a')
{
if($method == 'j')
{
return json_encode(get_object_vars($this));
}
else
{
return get_object_vars($this);
}
}
어느 쪽이든,get_object_vars()
아마 도움이 될 거예요.
$products=R::findAll('products');
$string = rtrim(implode(',', $products), ',');
echo $string;
제 방법은 다음과 같습니다.
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;
}
오브젝트 배열에 대해서는 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
'programing' 카테고리의 다른 글
open Session()과 get Current Session()의 휴지 상태 (0) | 2022.09.05 |
---|---|
'blur' 이벤트가 발생할 때 어떤 요소의 포커스가 *to*로 갔는지 어떻게 알 수 있습니까? (0) | 2022.09.05 |
VUE.JS - vNode 인수를 사용하여 알 수 없는 수량의 항목을 동적 탐색에 추가 (0) | 2022.09.05 |
Node.js 디렉토리에 있는 모든 파일 이름 목록을 가져오려면 어떻게 해야 합니까? (0) | 2022.09.05 |
N개의 어레이를 연결하는 가장 효율적인 방법은 무엇입니까? (0) | 2022.09.05 |