2013-10-05 86 views
1

我如何通過與PHP下面RAW數據循環,得到這樣的結果:如何遍歷原始JSON數據?

結果:

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"} 
+2

你的JSON似乎無效。它應該被封裝在'[...]' – Boaz

+0

這是一個問題,如果原始數據是在一個PHP文件中的RAW文本?已經添加了[...] – Stefan

回答

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 
+1

@DannyHearnah:已經修復;對不起,一段時間以來,這種PHP不直觀的做法已經遠遠不夠。 –

+0

我注意到:-)再次投票 –