0

When i run this code i get this error

PHP Fatal error: Cannot use object of type stdClass as array in line 18

<?php
$key = "*******";
$city = 'paris';
$url = "http://api.apixu.com/v1/forecast.json?key=$key&q=$city&days=7" ;

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$json_output=curl_exec($ch);
$weather = json_decode($json_output);
///echo "Temperature: " . $weather->forecast->forecastday[0]->hour[0]->time;

foreach($weather["hour"] as $hour) {
    if($hour['time'] == '2016-09-01 00:00') {
        echo "temp_c = " . $hour['temp_c'];
    }
}
?>

Second code I get this error

PHP Notice: Trying to get property of non-object in line 15

<?php
$key = "*****";
$city = 'paris';
$url = "http://api.apixu.com/v1/forecast.json?key=$key&q=$city&days=7" ;

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$json_output=curl_exec($ch);
$weather = json_decode($json_output);
///echo "Temperature: " . $weather->forecast->forecastday[0]->hour[0]->time;

foreach($weather->forecast->forecastday[0]->hour[0] as $hour) {
    if($hour->time == '2016-09-01 00:00') {
        echo $hour->temp_c;
    }
}
?>

I need to search the api for the given date and time and retrieve the temperature Can someone help me to debug this.

Blake
  • 2,294
  • 1
  • 16
  • 24
vivi
  • 3
  • 3
  • The error says it's not an array, so don't use syntax that infers it is in php. `$weather->hour` not `$weather["hour"]`. Your second block of code is trying to reference something that doesn't exist. Debug your code step by step. if `$weather->forecast->forecastday[0]` references something that isn't there, it's going to throw an error. – Blake Sep 01 '16 at 22:39
  • its `foreach($weather->forecast->forecastday[0]->hour as $hour)` – Kevin Sep 01 '16 at 22:42
  • @Ghost i changed that line and now it gives all the responses for every hour for temp_c. how to get only data for the given date and time ? – vivi Sep 01 '16 at 22:53

0 Answers0