如何循环原始JSON数据?

时间:2013-10-05 11:38:15

标签: php json loops

如何使用PHP循环访问以下RAW数据并获得此结果:

结果:

 NAME1 - SONG1
 NAME2 - SONG2
 NAME3 - SONG3

RAW数据:

{"artist":"NAME1","title":"SONG1","album":null,"royaltytrackid":null,"url":null,"image":"test1.jpg","time":1380910069,"localtime":"11:07 AM"},
{"artist":"NAME2","title":"SONG2","album":null,"royaltytrackid":null,"url":null,"image":"test2.jpg","time":1380909866,"localtime":"11:04 AM"},  
{"artist":"NAME2","title":"SONG3","album":null,"royaltytrackid":null,"url":null,"image":"test3.jpg","time":1380909864,"localtime":"11:04 AM"}

1 个答案:

答案 0 :(得分:5)

看起来您的输入数据缺少列表周围的[],因此在您将其解析为JSON之前,您需要添加以下内容:

$rawData = <<<EOL
{"artist":"NAME1","title":"SONG1","album":null,"royaltytrackid":null,"url":null,"image":"test1.jpg","time":1380910069,"localtime":"11:07 AM"},
{"artist":"NAME2","title":"SONG2","album":null,"royaltytrackid":null,"url":null,"image":"test2.jpg","time":1380909866,"localtime":"11:04 AM"},  
{"artist":"NAME2","title":"SONG3","album":null,"royaltytrackid":null,"url":null,"image":"test3.jpg","time":1380909864,"localtime":"11:04 AM"}
EOL;

$data = json_decode("[" . $rawData . "]");

foreach ($data as $item) {
    echo $item->artist, " - ", $item->title, "\n";
}

输出:

NAME1 - SONG1
NAME2 - SONG2
NAME2 - SONG3