2016-03-24 86 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

是的,我知道,但我认为第一个是更好的选择。无论如何,谢谢你指出。 –