Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在解码的json字符串PHP中访问字段_Php_Json - Fatal编程技术网

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

在解码的json字符串PHP中访问字段,php,json,Php,Json,我正在尝试使用php访问解码的json字符串中第一首歌曲的字段“id”。我尝试过所有可能的组合,比如: $response->songs[0]->id 这是我解码的json字符串: Array ( [response] => Array ( [status] => Array ( [version] => 4.2 [code] => 0 [message] => Success ) [songs] => Array ( [0] => Array (

我正在尝试使用php访问解码的json字符串中第一首歌曲的字段“id”。我尝试过所有可能的组合,比如:

$response->songs[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'];
解释

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

在您拥有的第一个数组中是“response”,这个数组包含其余的数组,因此

$id = $json_array['response']
从这个数组中,你必须在里面嵌套,直到你得到你想要的元素。它包含在另一个数组中,所以

$id = $json_array['response']['songs']
这首歌有几个元素以数字索引,因为你想要第一首歌的id,我们选择0元素

$id = $json_array['response']['songs'][0]
在此之后,您可以获得所需的元素:

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

json_解码返回数组,因此要访问它,请执行以下操作:

$id = $json_array['response']['songs'][0]['id'];
如果要以对象方式工作,则需要转换:

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

json\u decode
的第二个参数的值是多少?非常感谢!!我很快就会接受你的答复。