从json_decode获取单个元素


Fetch single element from json_decode

我有这个代码:

<?php
    $fql  = "SELECT url, normalized_url, share_count, like_count, comment_count, ";
    $fql .= "total_count, commentsbox_count, comments_fbid, click_count FROM ";
    $fql .= "link_stat WHERE url = 'http://apple.com'";
    $apifql = "https://api.facebook.com/method/fql.query?format=json&query=".urlencode($fql);
    $json = file_get_contents($apifql);
    $obj = json_decode($json);
    print_r($obj);
?>

输出:

Array ( [0] => stdClass Object ( [url] => http://apple.com [normalized_url] => http://www.apple.com/ [share_count] => 366493 [like_count] => 514795 [comment_count] => 298452 [total_count] => 1179740 [commentsbox_count] => 0 [comments_fbid] => 381975869314 [click_count] => 16558 ) )

如何在字符串中只定义commentsbox_count?我的数据库需要它。

您可以通过$obj[0]->commentsbox_count访问它。

顶级元素是一个单元素数组,唯一的关键字是0。这个元素是一个stdClass对象(它很像一个数组,但具有属性而不是数组元素),因此您可以使用->name访问该元素。