채택완료
json_decode 값에서 특정 값을 어떻게 불러올 수 있나요?
$data = json_decode($response, true);
print_r($data);
하면 나오는 결과입니다.
Array ( [statusCode] => 200 [body] => { "userid": [ "admin", "test"] })
여기서 admin을 얻고 싶어서
print_r($data['userid'][0]);
하면 나오는 결과가 없네요.
json_decode 값에서 특정 값을 어떻게 불러올 수 있나요?
답변 3개 / 댓글 5개
채택된 답변
+20 포인트
Copy
$user = json_decode($data['body']);
print_r($user->userid);
// 또는
$user = json_decode($data['body'], 1);
print_r($user['userid']);
답변에 대한 댓글 4개
$response라고 적어야 하는데, 임시값이라고 $temp라고 적었었네요.
어쨌거나 $data = json_decode($response, true); 에서 $data를 출력한 것이겠네요.
보면 알겠지만 $data['body']는 '문자열 값(JSON)'이에요.
그래서 처음 답변 남긴 것이 다시 한 번 json_decode()를 해서
필요한 값을 출력한 것이죠.
해당 변수의 값을 그대로 가져다가 실행해도 결과 잘 나오네요.
[code]
$data = json_decode($response, true);
$users = json_decode($data['body'], true);
print_r($users);
/*
Array
(
[userid] => Array
(
[0] => admin
[1] => test
)
)
*/
[/code]
어쨌거나 $data = json_decode($response, true); 에서 $data를 출력한 것이겠네요.
보면 알겠지만 $data['body']는 '문자열 값(JSON)'이에요.
그래서 처음 답변 남긴 것이 다시 한 번 json_decode()를 해서
필요한 값을 출력한 것이죠.
해당 변수의 값을 그대로 가져다가 실행해도 결과 잘 나오네요.
[code]
$data = json_decode($response, true);
$users = json_decode($data['body'], true);
print_r($users);
/*
Array
(
[userid] => Array
(
[0] => admin
[1] => test
)
)
*/
[/code]
$data = json_decode($response, true);
$data2 = json_decode($data , true);
print_r($data2);
echo $data2['userid'];
여기서 array 라고 나오면
echo $data2['userid]['admin'];
그게 아닌 [ "admin", "test"] 와 같이 나오면
$data3 = json_decode($data2);
echo $data3['admin'];
해보세요
답변을 작성하려면 로그인이 필요합니다.
Warning: Illegal string offset 'body' in /www/json.php on line 18