1

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

结果:

 NAME1 - SONG1
 NAME2 - SONG2
 NAME3 - SONG3

原始数据:

{"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"}
4

1 回答 1

5

看起来您的输入数据缺少列表周围的[and ],因此在将其解析为 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
于 2013-10-05T11:40:46.220 回答