source

json_decode()를 사용하여 개체 대신 배열을 만듭니다.

nicesource 2023. 5. 24. 22:12
반응형

json_decode()를 사용하여 개체 대신 배열을 만듭니다.

JSON 문자열을 배열로 디코딩하려고 하는데 다음 오류가 발생합니다.

치명적 오류: stdClass 유형의 개체를 배열로 사용할 수 없습니다.

코드는 다음과 같습니다.

$json_string = 'http://www.example.com/jsondata.json';

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
print_r($obj['Result']);

설명서에 따라 다음을 지정해야 합니다.true객체 대신 연상 배열을 원하는 경우 두 번째 인수로json_decode코드는 다음과 같습니다.

$result = json_decode($jsondata, true);

네가 원한다면integer속성 이름 대신 키를 입력합니다.

$result = array_values(json_decode($jsondata, true));

그러나 현재 디코드를 사용하면 객체로 액세스할 수 있습니다.

print_r($obj->Result);

이것을 먹어보세요.

$json_string = 'http://www.domain.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo "<pre>";
print_r($obj);

이것은 늦은 기여이지만 주조에 대한 타당한 사례가 있습니다.json_decode와 함께(array).
다음 사항을 고려합니다.

$jsondata = '';
$arr = json_decode($jsondata, true);
foreach ($arr as $k=>$v){
    echo $v; // etc.
}

한다면$jsondata빈 문자열로 반환되는 경우가 있습니다(내 경험에 따르면 종종 있음).json_decode돌아올 것입니다NULL오류가 발생하는 오류: 3행의 각()에 대해 제공된 인수가 잘못되었습니다.if/then 코드 또는 3진 연산자를 한 줄 추가할 수 있지만 IMO는 두 줄을...로 간단히 변경하는 것이 더 깨끗합니다.

$arr = (array) json_decode($jsondata,true);

그렇지 않은 한json_decode@TCB13이 지적한 바와 같이 성능에 부정적인 영향을 미칠 수 있는 수백만 개의 대규모 어레이를 한 번에 처리할 수 있습니다.

만약 당신이 5.2 이하의 php로 작업하고 있다면 이 자원을 사용할 수 있습니다.

http://techblog.willshouse.com/2009/06/12/using-json_encode-and-json_decode-in-php4/

http://mike.teczno.com/JSON/JSON.phps

PHP 설명서에 따름 json_decode함수에는 반환된 개체를 연관 배열로 변환하는 Associ라는 매개 변수가 있습니다.

 mixed json_decode ( string $json [, bool $assoc = FALSE ] )

연결 매개 변수가 다음과 같기 때문입니다.FALSE기본적으로 이 값을 다음으로 설정해야 합니다.TRUE배열을 검색하기 위해.

다음 코드의 예를 검토하여 의미를 참조하십시오.

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));

출력하는 항목:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

이렇게 하면 배열로도 변경됩니다.

<?php
    print_r((array) json_decode($object));
?>
json_decode($data, true); // Returns data in array format 

json_decode($data); // Returns collections 

따라서 배열을 원하는 경우 두 번째 인수를 'true'로 전달할 수 있습니다.json_decode기능.

json_decodesupport 두 번째 인수, 설정 시TRUE그것은 반환할 것입니다.Array대신에stdClass Object의 Manual 페이지를 확인합니다.json_decode지원되는 모든 인수와 세부 정보를 볼 수 있는 함수입니다.

예를 들어 다음을 시도합니다.

$json_string = 'http://www.example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, TRUE); // Set second argument as TRUE
print_r($obj['Result']); // Now this will works!

이것이 당신에게 도움이 되기를 바랍니다.

$json_ps = '{"courseList":[  
            {"course":"1", "course_data1":"Computer Systems(Networks)"},  
            {"course":"2", "course_data2":"Audio and Music Technology"},  
            {"course":"3", "course_data3":"MBA Digital Marketing"}  
        ]}';

Json 디코딩 기능 사용

$json_pss = json_decode($json_ps, true);

php의 JSON 배열에 대한 루프

foreach($json_pss['courseList'] as $pss_json)
{

    echo '<br>' .$course_data1 = $pss_json['course_data1']; exit; 

}

결과: 컴퓨터 시스템(네트워크)

PHP에서 json_decode는 json 데이터를 PHP 관련 배열로 변환합니다.
예:$php-array= json_decode($json-data, true); print_r($php-array);

이것 좀 드셔보세요.

<?php
$json_string = 'http://www.domain.com/jsondata.json';

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
echo "<pre>"; print_r($obj['Result']);
?>

다음과 같이 시도:

$json_string = 'https://example.com/jsondata.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata);
print_r($obj->Result);
foreach($obj->Result as $value){
  echo $value->id; //change accordingly
}

언급URL : https://stackoverflow.com/questions/5164404/use-json-decode-to-create-array-insead-of-an-object

반응형