当我尝试从数组中回显JSON对象时,它无法正常工作。在错误日志中,它给了我:
PHP Notice: Trying to get property of non-object in /home/zadmin/test.britishweb.co.uk/patchwork/featuredseries.php on line 48
对于我尝试呼应的每一个物体。这是我的代码:
<?php
$source = "http://prod.cloud.rockstargames.com/global/SC/events/eventschedule-game-en.json"; // Source URL will be unchanged most likely but placed in a variable just in case.
$ch = curl_init(); // Connect
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec ($ch);
curl_close ($ch);
$destination = "eventschedule-game-en.json";
$file = fopen($destination, "w+");
file_put_contents($destination, $data);
fclose($file);
$json = file_get_contents($destination);
$obj = json_decode($json, true);
var_dump($obj); // Debug option
?>
$obj
的转储:
{
"multiplayerEvents": [
{
"posixStartTime": 1498687200,
"posixEndTime": 1499720340,
"eventRosGameTypes": [
"gta5"
],
"eventPlatformTypes": [
"pcros",
"xboxone",
"ps4"
],
"displayName": "2x$ and RP Dawn Raid Adversary Mode",
"eventId": 20417,
"extraData": {
"eventType": "FeaturedJob"
}
}
]
}
然后我正在做HTML:
<div class="main_event">
<p id="name"><?php echo $obj["displayName"]; ?> Now playing on GTA V.</p>
<h2>Selected Platforms</h2>
<p id="platforms">The series is currently running on the following platforms:</p>
<ul>
<li><?php echo $obj->eventPlatformTypes[0]; ?></li>
<li><?php echo $obj->eventPlatformTypes[1]; ?></li>
<li><?php echo $obj->eventPlatformTypes[2]; ?></li>
</ul>
</div>
答案 0 :(得分:2)
您尝试访问$obj
作为对象而不是数组。您将true传递给json_decode()
的第二个参数的事实告诉您返回的对象是数组而不是对象。使用与在此行访问它们相同的方式访问属性:
<p id="name"><?php echo $obj["displayName"]; ?> Now playing on GTA V.</p>
另外,请注意没有&#34; displayName&#34;在$obj
。它是multiplayerEvents数组的一部分。因此,请访问您的$obj
数组,如下所示:
<div class="main_event">
<p id="name"><?php echo $obj["multiplayerEvents"][0]["displayName"]; ?> Now playing on GTA V.</p>
<h2>Selected Platforms</h2>
<p id="platforms">The series is currently running on the following platforms:</p>
<ul>
<li><?php echo $obj["multiplayerEvents"][0]["eventPlatformTypes"][0]; ?></li>
<li><?php echo $obj["multiplayerEvents"][0]["eventPlatformTypes"][1]; ?></li>
<li><?php echo $obj["multiplayerEvents"][0]["eventPlatformTypes"][2]; ?></li>
</ul>
</div>
另一个小小的注意事项。如果存在可变数量的类型/事件,您可能想要遍历您的eventPlatformTypes(甚至可能是您的multiplerEvents):
<ul>
<?php foreach ( $obj["multiplayerEvents"][0]["eventPlatformTypes"] as $platformType ): ?>
<li><?php echo $platformType; ?></li>
<?php endforeach; ?>
</ul>