PHP加载json数据,输出为空


PHP load json data, output is empty

我试图将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;
?>

如果我运行这个代码,我的输出是空的。谁能在正确的方向上帮助我?

根据RFC 4627(JSON规范),您的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;