无法打印简单的JSON?

时间:2015-11-20 17:58:43

标签: php

我知道这是基本的,但我不能解决错误,因为它不是我的区域。 我正在向服务器发送一些请求并打印响应,如下所示:

$rest = curl_init();  
 curl_setopt($rest,CURLOPT_URL,$url);  
 curl_setopt($rest,CURLOPT_GET,1);  
 curl_setopt($rest,CURLOPT_HTTPHEADER,$headers);  
 curl_setopt($rest,CURLOPT_SSL_VERIFYPEER, false);  
 curl_setopt($rest,CURLOPT_RETURNTRANSFER, true);  
 $response = curl_exec($rest);  
 $json = json_decode($response, true);

 echo $response;

我得到的地方:

{"results":[{"Devices":["52401E7E-C5D7","AE80C0F8-999E","764BFD92-9753","78A23379-2C14","EEA03545-5EB9","E18DDFEC-C3C9"],"UserID":"433011AC-228A-4931-8700-4D050FA18FC1","createdAt":"2015-11-04T15:06:33.564Z","objectId":"3os7BGxRoG","updatedAt":"2015-11-04T17:08:57.635Z"}]}

然后,我正在尝试打印JSON或其字段,但我什么都没得到:

  echo $json;
  echo $json['UserID'];
  echo $json['Devices'];

1 个答案:

答案 0 :(得分:1)

稍微澄清一下评论:

$str = '{"results":[{"Devices":["52401E7E-C5D7","AE80C0F8-999E","764BFD92-9753","78A23379-2C14","EEA03545-5EB9","E18DDFEC-C3C9"],"UserID":"433011AC-228A-4931-8700-4D050FA18FC1","createdAt":"2015-11-04T15:06:33.564Z","objectId":"3os7BGxRoG","updatedAt":"2015-11-04T17:08:57.635Z"}]}';
$json = json_decode($str, true); // to an associative array
// to echo the UserID
echo "userID : " . $json['results'][0]['UserID'];
// output: userID : 433011AC-228A-4931-8700-4D050FA18FC1

// to get the structure of the json array in general use print_r() as AbraCadaver pointed out
print_r($json);

在您的尝试中,您错过了results[0]部分。