문제

i have sometimes following error Fatal error: Cannot use object of type stdClass as array in.. with this function:

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);

but this error happen sometimes only for specific domains any help?

도움이 되었습니까?

해결책

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;
    }
}

다른 팁

According to the manual, there is an optional second boolean param which specifies whether the returned object should be converted to an associative array (default is false). If you want access it as an array then just pass true as the second param.

$data = json_decode(
    file_get_contents(
        "http://feeds.delicious.com/v2/json/urlinfo/data?url=$domain_name"
    ),
    true
);

Before using $data as array:

$data = (array) $data;

And then simply get your total_posts value from array.

$data[0]['total_posts']

json_decode returns an instance of stdClass, which you can't access like you would access an array. json_decode does have the possibility to return an array, by passing true as a second parameter.

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); 

or

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top