2015-04-29 75 views
3

我試圖訪問該解碼的json字符串中使用php的第一首歌的字段'id'。我已經嘗試了所有可能的組合像這樣的:解碼的json字符串中的訪問字段PHP

$響應 - >歌曲[0] - > ID

這是我的解碼JSON字符串:

Array (
[response] => Array (
[status] => Array (
[version] => 4.2 
[code] => 0 
[message] => Success 
) 
[songs] => Array (
[0] => Array (
[artist_id] => ARRH63Y1187FB47783 
[id] => SOKGWES13D647BE466 
[artist_name] => Kanye West 
[title] => All Of The Lights 
) 
[1] => Array (
[artist_id] => ARRH63Y1187FB47783 
[id] => SOHBKVU14509A9F6C3 
[artist_name] => Kanye West 
[title] => All Of The Lights 
) 
[2] => Array (
[artist_id] => ARRH63Y1187FB47783 
[id] => SODELAY13AD1ACC8CF 
[artist_name] => Kanye West 
[title] => All Of The Lights 
) 
[3] => Array (
[artist_id] => ARRH63Y1187FB47783 
[id] => SOUDIYM14B7C7B2D95 
[artist_name] => Kanye West 
[title] => All of the Lights 
) 
[4] => Array (
[artist_id] => ARRH63Y1187FB47783 
[id] => SOTEMPJ13DB921F71F 
[artist_name] => Kanye West 
[title] => All of the Lights (
Remix 
) 
) 
[5] => Array (
[artist_id] => ARRH63Y1187FB47783 
[id] => SOXIDRL13CCFBBC829 
[artist_name] => Kanye West 
[title] => All Of The Lights 
[LbLuke Rmx] 
) 
[6] => Array (
[artist_id] => ARRH63Y1187FB47783 
[id] => SOTJZSO12D857905F6 
[artist_name] => Kanye West 
[title] => All Of The Lights (
Interlude 
) 
) 
[7] => Array (
[artist_id] => ARVCDGF12FE08689BA 
[id] => SOGLUJD130516E0D00 
[artist_name] => Made famous by Kanye West 
[title] => All of the lights 
) 
) 
) 
) 

在此先感謝

+0

什麼是'json_decode'的第二個參數的值? –

回答

2
$id = $json_array['response']['songs'][0]['id']; 

說明

看看反應,你的反應是一個多維ARRA這意味着你有一個由幾個數組組成的數組,每個數組可以包含一個或多個數組。

在你的第一個數組是「響應」,這其中包含了他們的休息,所以..

$id = $json_array['response'] 

此數組你,直到你得到你想要的元素裏面去築巢。其中包含到另一個陣列的歌曲,所以..

$id = $json_array['response']['songs'] 

這其中有幾個要素通過數字索引,只要你想從我們選擇的0元素的第一首歌曲的編號,

$id = $json_array['response']['songs'][0] 

後這個你可以得到元素你想要的:

$id = $json_array['response']['songs'][0]['id']; 
+0

非常感謝! 我很快就會接受你的回答。 – Beunzor

0

的json_decode返回數組,所以訪問你這樣做:

$id = $json_array['response']['songs'][0]['id']; 

如果你想在對象的方式來工作,你需要轉換:

$object = (object) $json_array; 
$object->response->songs[0]->id