【问题标题】:Fatal error: Cannot use object of type stdClass as array in C:\xampp\htdocs\aiw\index.php致命错误:不能在 C:\xampp\htdocs\aiw​​\index.php 中使用 stdClass 类型的对象作为数组
【发布时间】:2017-11-05 10:15:48
【问题描述】:
<?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;
?>

当我尝试运行网络时,它显示了这个问题 致命错误:不能在第 16 行的 C:\xampp\htdocs\aiw​​\index.php 中使用 stdClass 类型的对象作为数组 我希望你不要不喜欢,因为我是一个新的学习者

【问题讨论】:

  • 提供您获得的 JSON 输出示例。此外,公开您的 API 密钥通常是个坏主意,请用空字符串或星号行替换它

标签: php arrays json object


【解决方案1】:

这个错误:

Cannot use object of type stdClass as array

表示它不是一个数组,它是一个对象

改变这个:

 echo $weather_details[0]->EffectiveDate;

到这里

echo $weather_details->Headline->EffectiveDate

【讨论】:

    【解决方案2】:

    当您在 php 中解码 json 时(使用 json_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}"),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'];
    ?>
    

    【讨论】:

    • 警告:file_get_contents(http://******):打开流失败:HTTP 请求失败! HTTP/1.1 503 在第 13 行的 C:\xampp\htdocs\aiw​​\index.php 中未经授权
    猜你喜欢
    • 2016-05-16
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2013-07-05
    • 1970-01-01
    • 2018-08-25
    相关资源
    最近更新 更多