如何使用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"}
答案 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