2015-04-29 47 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