2017-07-02 82 views
0

當我試圖從一個不正常的陣列呼應JSON對象。在錯誤日誌中,它給了我這個:我在做這個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> 
+1

你能後的var_dump($ OBJ)的'輸出;' ? – FrankerZ

+0

'file_put_contents()'不要求你打開seperately – RiggsFolly

+0

您的非對象錯誤是造成文件'$ obj-> eventPlatformTypes'當'obj'是一個數組 –

回答

2

你試圖訪問$obj作爲對象而不是數組。事實上,你傳遞給第二個參數json_decode(),告訴你返回的對象是一個數組而不是一個對象。使用您訪問了它們在這條線以同樣的方式訪問屬性:

<p id="name"><?php echo $obj["displayName"]; ?> Now playing on GTA V.</p> 

此外,要知道,沒有對$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> 
+0

謝謝你這麼多的清除此爲我和提供更直觀的處理eventPlatformTypes的方法。非常感激! – ravetta

相關問題