Accessing field in decoded json string php

I am trying to access the 'id' field of the first song in this decrypted json string using php. I've tried every possible combination like this one:

$ response-> songs [0] → ID

This is my decoded json string:

   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
)
)
)
)

      

Thank you in advance

+3


source to share


2 answers


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

      

Explanation

Take a look at the answer, your answer is a multidimensional array. This means that you have an array formed by several arrays, and each of them can contain one or more arrays.

In the first array you have the "answer", this one contains the rest, so ..

$id = $json_array['response']

      

from that array, you have to step inside until you get your desired element. What's in the songs of other arrays, so ..



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

      

This one has multiple numbers indexed items, since you want the id from the first song we select item 0,

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

      

after that you can get the element you want:

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

      

+2


source


The returned array is json_decode, so to access you do like this:

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

      



If you want to work on an object, you need to convert:

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

      

0


source







All Articles