2

I'm using The Echo Nest API to find similar artists. The response looks like:

{"response": {"status": {"version": "4.2", "code": 0, "message": "Success"}, "artists": [{"name": "Audio Adrenaline", "id": "ARGEZ5E1187FB56F38"}, {"name": "Tree63", "id": "ARWKO2O1187B9B5FA7"}]}}

How can I take the artists it results and put them into an array? So I can then echo them later like:

echo $artist[0];
austinh
  • 1,061
  • 6
  • 13
  • 34

3 Answers3

6

You just need to use json_decode() with the second parameter set to TRUE.

$str = '...';
$json = json_decode($str, TRUE);
$artist = $json['response']['artists'];    
//$artist = json_decode($str, TRUE)['response']['artists']; as of PHP 5.4

print_r($artist);

Output:

Array
(
    [0] => Array
        (
            [name] => Audio Adrenaline
            [id] => ARGEZ5E1187FB56F38
        )

    [1] => Array
        (
            [name] => Tree63
            [id] => ARWKO2O1187B9B5FA7
        )

)

Codepad!

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
2

json_decode() is what you need

$artist = json_decode($json);

or as an associative array

$artist = json_decode($json, true);
David Barker
  • 14,484
  • 3
  • 48
  • 77
0

Use json_decode, found here.

Sample:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));

Output:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
TheLettuceMaster
  • 15,594
  • 48
  • 153
  • 259