json_encode/json_decode - PHP의 어레이 대신 stdClass를 반환합니다.
다음의 작은 스크립트를 참조해 주세요.
$array = array('stuff' => 'things');
print_r($array);
//prints - Array ( [stuff] => things )
$arrayEncoded = json_encode($array);
echo $arrayEncoded . "<br />";
//prints - {"stuff":"things"}
$arrayDecoded = json_decode($arrayEncoded);
print_r($arrayDecoded);
//prints - stdClass Object ( [stuff] => things )
PHP가 JSON 개체를 클래스로 바꾸는 이유는 무엇입니까?
이 어레이는json_encoded
그리고나서json_decoded
정확히 같은 결과를 얻을 수 있을까요?
의 두 번째 파라미터를 자세히 살펴봅니다.json_decode($json, $assoc, $depth)
https://secure.php.net/json_decode 에서 참조해 주세요.
$arrayDecoded = json_decode($arrayEncoded, true);
배열을 나타냅니다.
실제 질문에 답하려면:
PHP가 JSON 개체를 클래스로 바꾸는 이유는 무엇입니까?
인코딩된 JSON의 출력을 자세히 살펴봅니다. OP가 제공하는 예를 조금 확장했습니다.
$array = array(
'stuff' => 'things',
'things' => array(
'controller', 'playing card', 'newspaper', 'sand paper', 'monitor', 'tree'
)
);
$arrayEncoded = json_encode($array);
echo $arrayEncoded;
//prints - {"stuff":"things","things":["controller","playing card","newspaper","sand paper","monitor","tree"]}
JSON 포맷은 JavaScript(ECMAScript Programming Language Standard)와 동일한 표준에서 파생되었으며 포맷을 살펴보면 JavaScript와 유사합니다.값이 "things"인 속성 "stuff"를 가진 JSON 개체({}
= 개체)이며 값이 문자열 []
배열(= 배열)인 속성 "things"를 가집니다.
JSON(JavaScript)은 연관 배열은 인덱스된 배열만 인식하지 않습니다.따라서 JSON이 PHP 관련 배열을 인코딩할 때 이 배열을 포함하는 JSON 문자열이 "개체"로 생성됩니다.
이제 JSON을 다시 디코딩합니다.json_decode($arrayEncoded)
디코드 함수는 이 JSON 문자열이 (PHP 배열)에서 어디서 왔는지 알 수 없기 때문에 알 수 없는 개체로 디코딩하고 있습니다.stdClass
PHP로 설정합니다.보시다시피 문자열의 "things" 배열은 색인화된 PHP 배열로 디코딩됩니다.
다음 항목도 참조해 주세요.
- RFC 4627 - JavaScript 객체용 응용 프로그램/json 미디어 유형
- RFC 7159 - JavaScript Object Notation(JSON; 자바스크립트
- PHP 매뉴얼 - 어레이
https://www.randomlists.com/things의 '물건'에 감사드립니다.
전술한 바와 같이 여기에 두 번째 파라미터를 추가하여 어레이를 반환하는 것을 나타낼 수 있습니다.
$array = json_decode($json, true);
많은 사람들이 대신 결과를 캐스팅하는 것을 선호할 수 있습니다.
$array = (array)json_decode($json);
읽기가 더 쉬울 수도 있어요.
tl;dr: JavaScript는 연관 배열을 지원하지 않으므로 JSON도 지원하지 않습니다.
역시 JSAAN이 아니라 JSON입니다. : )
따라서 PHP는 JSON으로 인코딩하기 위해 어레이를 개체로 변환해야 합니다.
var_dump(json_decode('{"0":0}')); // output: object(0=>0)
var_dump(json_decode('[0]')); //output: [0]
var_dump(json_decode('{"0":0}', true));//output: [0]
var_dump(json_decode('[0]', true)); //output: [0]
json을 배열로 디코딩하면 이 상황에서 정보가 손실됩니다.
이 블로그 투고에는 PHP 4 json 인코딩/디코딩 라이브러리(PHP 5 역호환 가능)도 기재되어 있습니다.PHP4(2009년 6월)에서 json_encode() 및 json_decode()를 사용합니다.
구체적인 코드는 Michal Migurski와 Matt Knapp에 의해 작성되었습니다.
- JSON-PHP / 2005년1월
- 코드: http://mike.teczno.com/JSON/JSON.phps
- Pear Proposal : http://pear.php.net/pepr/pepr-proposal-show.php?id=198
- Pear 패키지: http://pear.php.net/package/Services_JSON
언급URL : https://stackoverflow.com/questions/2281973/json-encode-json-decode-returns-stdclass-instead-of-array-in-php
'programing' 카테고리의 다른 글
Javascript에서 난수 생성기 시드하기 (0) | 2022.12.27 |
---|---|
MySQL - 일대일 관계 (0) | 2022.12.27 |
Hamcrest 비교 컬렉션 (0) | 2022.12.07 |
이름, 성, 시에서 보낸 이메일 목록을 작성하려면 어떻게 해야 합니까? (0) | 2022.12.07 |
Java에서 문자열 표시 너비 계산 (0) | 2022.12.07 |