3

次のエラーが発生することがあります 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);

しかし、このエラーは特定のドメインでのみ発生することがあります。

4

5 に答える 5

3

マニュアルによるとboolean、返されたオブジェクトを連想配列に変換するかどうかを指定するオプションの 2 番目のパラメーターがあります (デフォルトはfalse )。配列としてアクセスする場合はtrue、2 番目のパラメーターとして渡すだけです。

$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 のインスタンスを返します。2 番目のパラメーターとして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 に答える