我尝试将我的JSON文件中的数据加载到php中,但我的问题是如何出错?
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;
?>
答案 0 :(得分:1)
根据RFC 4627(JSON specification),您的JSON输入无效。所以正确的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;