2013-02-04 34 views
0

我不斷收到這個錯誤我的Twitter插件:PHP - 無法使用類型stdClass的對象作爲數組

致命錯誤:無法使用類型stdClass的對象爲數組中的C:......上線72

它只顯示有時,但我的推特計數器不會改變相當長的時間。請你幫忙嗎?代碼如下,關於行在中間: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; ?> 

回答

0

數組和對象具有不同的語法:

$array = array(
    'foo' => 'bar', 
); 
$object = (object)$array; 

var_dump($array['foo'], $object->foo); 

無法在該線路上使用類型stdClass的的對象作爲陣列錯誤消息指的是數組語法(方括號):

update_option('pyre_twitter_followers', $json[0]->user->followers_count); 
              ^^^ 

如果它的工作原理有些時候,再有就是情況$json是一個對象和情況下,當它是一個數組。可變來自這裏:

$json = json_decode($api['body']); 

docs for json_decode()告訴我們,第二參數決定是否生成一個對象或一個陣列:

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.

0

json_decode()函數有兩個參數。如果你想要一個數組表示,你需要通過true作爲第二個參數值。否則它默認生成一個對象表示。

http://php.net/json_decode

+0

感謝您的努力。那麼修改json-decode()函數就可以了,如下所示: json_decode($ api,true) – slurm

相關問題