JSON对PHP数组的响应

时间:2013-09-10 18:58:42

标签: php json

我正在使用The Echo Nest API找到类似的艺术家。回复如下:

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

如何将结果的艺术家带入阵列?所以我可以稍后回复它们:

echo $artist[0];

3 个答案:

答案 0 :(得分:5)

您只需使用json_decode()并将第二个参数设置为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);

输出:

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

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

)

Codepad!

答案 1 :(得分:1)

你需要

json_decode()

$artist = json_decode($json);

或作为关联数组

$artist = json_decode($json, true);

答案 2 :(得分:0)

使用json_decode,找到here

样品:

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

var_dump(json_decode($json));

<强>输出

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}