2016-03-24 69 views
-1

我嘗試從我的JSON文件加載數據到php,但我的oupt是emtpy什麼是錯誤?PHP加載json數據,輸出爲空

JSON:

{ 
    "drinks":[ 

    "1" {"coffee": "zwart", "country":"afrika"}, 

    "2" {"tea": "thee", "country":"china"}, 

    "3" {"water": "water", "country":"netherlands"}, 
    ] 
} 

PHP:

<?php 
$str = file_get_contents('data.json'); 
$json = json_decode($str, true); 
$drinks = $json['drinks'][0][coffee]; 

echo $drinks; 
?> 
+1

嘗試添加冒號在'「1」之後''像這樣:'「1」:{....' – Veniamin

+4

看起來像這個json是無效的。 –

+0

Json無效! –

回答

1

你的JSON輸入無效根據RFC 4627(JSON specification)。所以,正確的JSON字符串必須是:

{"drinks":[ 
       {"coffee": "zwart", "country":"afrika"}, 
       {"tea": "thee", "country":"china"}, 
       {"water": "water", "country":"netherlands"} 
      ] 
    } 

因此您的代碼將工作:

$str = file_get_contents('data.json'); 
$json = json_decode($str, true);  
$drinks = $json['drinks'][0]['coffee']; 
echo $drinks; 

或者至少,你必須格式化你的JSON字符串象下面這樣:

{ 
    "drinks":[  
     { 
     "1": {"coffee": "zwart", "country":"afrika"},  
     "2": {"tea": "thee", "country":"china"},  
     "3": {"water": "water", "country":"netherlands"} 
     } 
    ] 
} 

你可以通過這種方式獲取數據:

$str = file_get_contents('data.json'); 
$json = json_decode($str, true); 
$drinks = $json['drinks'][0]['1']['coffee']; 
echo $drinks; 
+1

也許只是一個語言障礙的東西,但你的答案的後半部分是什麼意思?它「必須」是第一個答案,但它至少必須像第二個答案那樣格式化? – Phil

+0

是的,我知道,但我認爲第一個是更好的選擇。無論如何,謝謝你指出。 –