致命错误:无法在C:\xampp\htdocs\aiw\index.php中将stdClass类型的对象用作数组

致命错误:无法在C:\xampp\htdocs\aiw\index.php中将stdClass类型的对象用作数组,php,arrays,json,object,Php,Arrays,Json,Object,在php中解码json时(使用json\u decode)。它将以对象的形式返回数据。如果希望数据作为数组,则需要将第二个参数作为true传递。因此,请按以下方式更改代码: <?php echo "<h1>What's The Weather Like?</h1>"; define('API_KEY','********'); $apikey = API_KEY; $user_ip = '183.91.3.13'; // Remove comment to us

在php中解码json时(使用
json\u decode
)。它将以对象的形式返回数据。如果希望数据作为数组,则需要将第二个参数作为true传递。因此,请按以下方式更改代码:

<?php
echo "<h1>What's The Weather Like?</h1>";
define('API_KEY','********');

$apikey = API_KEY;

$user_ip = '183.91.3.13'; // Remove comment to use this to test when you put 
   this file in localhost
 //$user_ip = $_SERVER['REMOTE_ADDR']; // Comment out this line if you test 
 in your localhost
  $details = 
 json_decode(file_get_contents("http://ipinfo.io/{$user_ip}/json"));
 $city_name = $details->city;
 $loc_details = 
json_decode(file_get_contents("http://dataservice.accuweather.com/locations/v1/ cities/search?q={$city_name}&apikey={$apikey}"));
 $loc_key = $loc_details[0]->Key;
 $weather_details = 


json_decode(file_get_contents("http://dataservice.accuweather.com/forecasts/v1/daily/1day/{$loc_key}?apikey={$apikey}"));
 // print_r($weather_details);
 //  $result = json_decode($data, true);
 echo $weather_details[0]->EffectiveDate;
?>
此错误:

<?php
echo "<h1>What's The Weather Like?</h1>";
define('API_KEY','**********');

$apikey = API_KEY;

$user_ip = '183.91.3.13'; // Remove comment to use this to test when you put 
   this file in localhost
 //$user_ip = $_SERVER['REMOTE_ADDR']; // Comment out this line if you test 
 in your localhost
  $details = 
 json_decode(file_get_contents("http://ipinfo.io/{$user_ip}/json"));
 $city_name = $details->city;
 $loc_details = 
json_decode(file_get_contents("http://dataservice.accuweather.com/locations/v1/ cities/search?q={$city_name}&apikey={$apikey}"),true); //change here
 $loc_key = $loc_details[0]['Key'];
 $weather_details = 


json_decode(file_get_contents("http://dataservice.accuweather.com/forecasts/v1/daily/1day/{$loc_key}?apikey={$apikey}"),true); //change here
 // print_r($weather_details);
 //  $result = json_decode($data, true);
 echo $weather_details[0]['EffectiveDate'];
?>
意味着它不是数组,而是对象

更改此项:

Cannot use object of type stdClass as array
对此

 echo $weather_details[0]->EffectiveDate;

提供您获得的JSON输出示例。此外,将API密钥公开给公众通常是个坏主意,请将其替换为空字符串或一行starswaning:file_get_contents(http://*****):无法打开流:http请求失败!HTTP/1.1 503在C:\xampp\htdocs\aiw\index.php第13行未经授权
echo $weather_details->Headline->EffectiveDate