3

我有时会出现以下错误致命错误:无法使用 stdClass 类型的对象作为数组 in.. 使用此函数:

function deliciousCount($domain_name)
{
    $data = json_decode(
        file_get_contents(
            "http://feeds.delicious.com/v2/json/urlinfo/data?url=$domain_name"
        )
    );
    if ($data) {
        return $data[0]->total_posts;
    } else {
        return 0;
    }
}

$delic = deliciousCount($domain_name);

但是这个错误有时只发生在特定域有什么帮助吗?

4

5 回答 5

3

根据手册,有一个可选的第二个boolean参数指定是否应将返回的对象转换为关联数组(默认为false)。如果您想将其作为数组访问,则只需true作为第二个参数传递。

$data = json_decode(
    file_get_contents(
        "http://feeds.delicious.com/v2/json/urlinfo/data?url=$domain_name"
    ),
    true
);
于 2011-12-13T08:29:23.840 回答
2

在使用 $data 作为数组之前:

$data = (array) $data;

然后只需从数组中获取您的 total_posts 值。

$data[0]['total_posts']
于 2011-12-13T08:49:15.663 回答
1
function deliciousCount($domain_name) {
    $data = json_decode(
        file_get_contents(
            "http://feeds.delicious.com/v2/json/urlinfo/data?url=$domain_name"
        )
    );
    // You should double check everything because this delicious function is broken
    if (is_array($data) && isset($data[ 0 ]) &&
        $data[ 0 ] instanceof stdClass  && isset($data[ 0 ]->total_posts)) {
        return $data[ 0 ]->total_posts;
    } else {
        return 0;
    }
}
于 2011-12-13T09:33:56.703 回答
0

json_decode返回 stdClass 的实例,您不能像访问数组一样访问它。json_decode确实有可能通过true作为第二个参数传递来返回一个数组。

于 2011-12-13T08:28:57.683 回答
-1
function deliciousCount($domain_name)
{
    $data = json_decode(
        file_get_contents(
            "http://feeds.delicious.com/v2/json/urlinfo/data?url=$domain_name"
        )
    );
    if ($data) {
        return $data->total_posts;
    } else {
        return 0;
    }
}

$delic = deliciousCount($domain_name); 

或者

function deliciousCount($domain_name)
{
    $data = json_decode(
        file_get_contents(
            "http://feeds.delicious.com/v2/json/urlinfo/data?url=$domain_name",true
        )
    );
    if ($data) {
        return $data['total_posts'];
    } else {
        return 0;
    }
}

$delic = deliciousCount($domain_name);
于 2011-12-13T08:41:30.487 回答