繁体   English   中英

访问解码的json字符串PHP中的字段

[英]Accessing field in decoded json string PHP

我正在尝试使用php访问此解码的json字符串中第一首歌的字段'id'。 我尝试了所有可能的组合,如下所示:

$响应 - >歌曲[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
)
)
)
)

提前致谢

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

说明

看看响应,你的响应是一个多维数组,这意味着你有一个由几个数组组成的数组,每个数组都可以包含一个或多个数组。

在第一个数组中你有“响应”,这个包含其余的,所以..

$id = $json_array['response']

从这个数组你必须嵌套在里面,直到你得到你想要的元素。 哪个包含在另一个数组歌曲中,所以..

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

这个有几个用数字索引的元素,因为你想要第一首歌我们选择0元素的id,

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

在此之后,您可以获得所需的元素:

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

json_decode返回数组,所以要访问你这样做:

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

如果你想以Object方式工作,你需要转换:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM