带有JSON对象的PHP输出有问题(可能是数组?)

时间:2015-12-15 21:46:52

标签: php json

我在使用PHP输出JSON对象(可能是数组?)时遇到了麻烦。我的问题是:如何使用PHP从以下(缩短的)JSON对象中仅获取displayName?

{"Response":
  {"results":
    [{"user":
      {"membershipId":"6343960","displayName":"J Raider"},"hasPendingApplication":false},
     {"user":
      {"membershipId":"4479502","displayName":"T Ellis"},"hasPendingApplication":false}]
  }
}

到目前为止我已尝试过:

var_dump($json); 
echo $json; 
echo $json->Response->results->user->displayName;
echo $json->Response->results[0]->user->displayName; 
echo $json->Response->results[0]->user[0]->displayName; 
echo json_encode($json, JSON_PRETTY_PRINT);
print_r($json)

我的结果是" null" " NULL"或者根本没有输出。 我使用以下代码从Bungie API中提取:

<?php 
    $apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.bungie.net/Platform/Group/1179713/Members/?lc=en&fmt=true&currentPage=1&platformType=1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-API-Key: ' . $apiKey));

$json = json_decode(curl_exec($ch)); // edited to correct curl_init to  curl_exec

var_dump($json);

?>

我的目标是使用PHP作为Web服务。 Bungie API文档说JavaScript GET请求不起作用,所以我想在请求和输出时坚持使用PHP。

澄清我的问题:如何使用PHP从此JSON对象输出displayName?

先谢谢你的帮助,如果我需要澄清任何问题,请告诉我。

2 个答案:

答案 0 :(得分:0)

只需使用json_decode()函数,然后在结果中迭代遍历数组

$decoded = json_decode($json);//this will give anarray from your json 
$obj = $decoded->Response->results;
foreach ($obj as $ar) {
  $displayName = $ar->user->displayName;
  echo $displayName . "<br>";
}

如果您需要更多帮助,请与我们联系

答案 1 :(得分:0)

我很确定这是失败的,因为你没有执行你的卷曲帖子:

UITabBarController

应该是

$json = json_decode(curl_init($ch));