2014-03-05 24 views
1

以下JSON如何解析以下JSON在PHP如何解析在PHP

[ 
{ "user":"John", "age":22, "country":"United States" }, 
{ "user":"Will", "age":27, "country":"United Kingdom" }, 
{ "user":"Abiel", "age":19, "country":"Mexico" }, 
{ "user":"Rick", "age":34, "country":"Panama" }, 
{ "user":"Susan", "age":23, "country":"Germany" }, 
{ "user":"Amy", "age":43, "country":"France" } 
] 

我用下面的代碼,這一點,但它沒有工作

$jsonData = file_get_contents("http://localhost/attendance1/a.json"); 
$phpArray = json_decode($jsonData, true); 
echo $phpArray; 
foreach ($phpArray as $key => $value) { 
    echo "<h2>$key</h2>"; 
    foreach ($value as $k => $v) { 
     echo "$k | $v <br />"; 
    } 
} 
+1

這不是有效的JSON。 – Barmar

+1

數組應該用''[']'而不是'{...}'包圍。 – Barmar

+0

這不是有效的JSON字符串。 – bspellmeyer

回答

3

你必須改變你的json主項目數組(而不是對象)使用[],而不是{}。

[ 
{ "user":"John", "age":22, "country":"United States" }, 
{ "user":"Will", "age":27, "country":"United Kingdom" }, 
{ "user":"Abiel", "age":19, "country":"Mexico" }, 
{ "user":"Rick", "age":34, "country":"Panama" }, 
{ "user":"Susan", "age":23, "country":"Germany" }, 
{ "user":"Amy", "age":43, "country":"France" } 
] 
+0

對不起,它的工作..謝了 – azhar

+0

例如:http://codepad.org/CSL3b8yk – Leabdalla

1

它不是一個有效的JSON格式,嘗試這樣的:

[ 
{ "user":"John", "age":22, "country":"United States" }, 
{ "user":"Will", "age":27, "country":"United Kingdom" }, 
{ "user":"Abiel", "age":19, "country":"Mexico" }, 
{ "user":"Rick", "age":34, "country":"Panama" }, 
{ "user":"Susan", "age":23, "country":"Germany" }, 
{ "user":"Amy", "age":43, "country":"France" } 
] 

(看方括號中)

「[]」括號表示一個LIST,而「{}」表示一個對象。 它們之間的區別是對象包含「鍵」:「值」對,而列表返回的項目沒有一個鍵