2017-04-02 59 views
0

所以我試圖解析一些Youtube API返回的JSON。我一直在理解如何解析PHP中的JSON,並且我似乎無法弄清楚。在PHP中用JSON解析括號外的數據

這是基本的API輸出:

{ 
"kind": "youtube#channelListResponse", 
"etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/mgiCAEvrnAFhKSCga80wVfAbUtc\"", 
"pageInfo": { 
    "totalResults": 1, 
    "resultsPerPage": 1 
}, 
"items": [ 
    { 
    "kind": "youtube#channel", 
    "etag": "\"uQc-MPTsstrHkQcRXL3IWLmeNsM/cndol6pHIKmkRCizokwycOOUr2E\"", 
    "id": "SWMb9NxQL9I6c", 
    "snippet": { 
    "title": "Koffee With Karan", 
    "description": "Catch Karan Johar chat up Bollywood, secrets revealed and stories told , that's how the world will remember Koffee with Karan", 
    "thumbnails": { 
    "default": { 
     "url": "https://i.ytimg.com/sh/554333074/showposter_thumb.jpg" 
    }, 
    "medium": { 
     "url": "https://i.ytimg.com/sh/554333074/showposter.jpg" 
    }, 
    "high": { 
     "url": "https://i.ytimg.com/sh/554333074/showposter_hq.jpg" 
    } 
    } 
    } 
    } 
] 
} 

我想要得到的是在「片段」,我需要的標題,描述和縮略圖幾乎一切。我一直在試圖訪問它是這樣的:

$getjson = file_get_contents('https://www.googleapis.com/youtube/v3/channels?part=snippet&id=SWMb9NxQL9I6c&key=mykey'); 
$data = json_decode($getjson,true); 

echo $data['items'][0]['snippet'][0]['title']; 

甚至試圖像

echo $data['items']->snippet->title; 

事情我已經發現了大量的文章沒有解釋如何,但似乎工作或意義。首先,「項目」數據不在起始的{}括號內,我沒有真正能夠找到任何關於它的信息。

任何幫助,主要是關於這是如何工作的解釋是真棒。我只想了解訪問這些東西所需的語法。

+0

關閉......片段是不是一個數組而是一個對象,所以你不['snippet'] [0] ['title']'just'['snippet'] ['title']' – Augwa

回答

3

你快到了。嘗試$data['items'][0]['snippet']['title']

  1. json_decode(..., true)true將返回associative array
  2. 使用[]來訪問數組值。
  3. 任何東西{}手段,您可以訪問使用鍵,像['snippet'] &任何東西[]您可以訪問使用index[0][1]

這可能不是很好的解釋。希望這有點可以理解。

+0

使用'json_decode'的第二個參數作爲'true',將輸出作爲對象而不是數組。 –

+0

@AmirZojaji從手冊中'當TRUE時,返回的對象將被轉換爲關聯數組。我確定'true'會將對象轉換爲數組。請糾正我,如果我錯了 –

+0

Aaah,太棒了!我已經知道添加true會將它作爲數組返回。在我使用'$ data ['items'] [0] ['snippet'] [0] ['title']'之前,它一直在說未知的索引0,所以我猜想它是第一個0。還要感謝@AmirZojaji! – s1h4d0w

0

在你的代碼中items有一個數組值,但是snippet是一個不是數組的結構。因此,必須使用:

echo $data->items[0]->snippet->title; 

,或者如果你有json_decode第二個參數true你可以寫:

echo $data['items'][0]['snippet']['title']; 
+0

感謝您的回答,我現在明白了! – s1h4d0w