簡體   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