grigione
grigione

Reputation: 717

Cannot use object of type stdClass as array in

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?

Upvotes: 3

Views: 3454

Answers (5)

Saxoier
Saxoier

Reputation: 1287

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

Upvotes: 2

wormhit
wormhit

Reputation: 3837

Before using $data as array:

$data = (array) $data;

And then simply get your total_posts value from array.

$data[0]['total_posts']

Upvotes: 2

beta
beta

Reputation: 268

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

Upvotes: -1

Yes Barry
Yes Barry

Reputation: 9876

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

Upvotes: 3

Wesley van Opdorp
Wesley van Opdorp

Reputation: 14951

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.

Upvotes: 0

Related Questions