不能使用stdClass类型的对象作为数组
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?
我有时会出现以下错误 Fatal错误:无法使用stdClass类型的对象作为数组... 使用此函数 : p>
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; \ n}
$ delic = deliciousCount($ domain_name);
code> pre>
但有时只针对特定域发生此错误
nn帮助? p>
div>
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;
}
}
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.
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
);
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);
Before using $data as array:
$data = (array) $data;
And then simply get your total_posts value from array.
$data[0]['total_posts']