I keep getting this error for my twitter plugin:
Fatal error: Cannot use object of type stdClass as array in C:.... on line 72
It only shows at times, however my twitter counter doesn't change for a considerable time. Please can you help? The code is below, regarding line is in the middle: update_option('pyre_twitter_followers', $json[0]->user->followers_count);
<?php if(get_option('pyre_twitter_id')): ?>
<div class="social-box">
<a href='http://twitter.com/<?php echo get_option('pyre_twitter_id'); ?>'>
<img src="<?php echo get_template_directory_uri(); ?>/images/twitter.png" alt="Follow us on Twitter" width="48" height="48" /></a>
<?php
$interval = 3600;
if($_SERVER['REQUEST_TIME'] > get_option('pyre_twitter_cache_time')) {
@$api = wp_remote_get('http://twitter.com/statuses/user_timeline/' . get_option('pyre_twitter_id') . '.json');
@$json = json_decode($api['body']);
if(@$api['headers']['x-ratelimit-remaining'] >= 1) {
update_option('pyre_twitter_cache_time', $_SERVER['REQUEST_TIME'] + $interval);
update_option('pyre_twitter_followers', $json[0]->user->followers_count);
}
}
?>
<div class="social-box-text">
<span class="social-arrow"></span>
<span class="social-box-descrip"><?php _e('Follow us on Twitter', 'pyre'); ?></span>
<span class="social-box-count"><?php echo get_option('pyre_twitter_followers'); ?> <?php _e('Followers', 'pyre'); ?></span>
</div>
</div>
<?php endif; ?>
Arrays and objects have different syntaxes:
$array = array(
'foo' => 'bar',
);
$object = (object)$array;
var_dump($array['foo'], $object->foo);
A Cannot use object of type stdClass as array error message on this line refers to the array syntax (square brackets):
update_option('pyre_twitter_followers', $json[0]->user->followers_count);
^^^
If it works some times, then there're cases where $json
is an object and cases when it's an array. The variable comes from here:
$json = json_decode($api['body']);
The docs for json_decode()
inform us that second parameter decides whether to generate an object or an array:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
assoc When
TRUE
, returned objects will be converted into associative arrays.
The json_decode()
function takes two parameters. If you want an array representation, you need to pass true
as the second parameter value. Otherwise it generates an object representation by default.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.