我想知道如何计算有多少人在Instagram上关注某人,并将数字放在一个变量中,Instagram给出了这个链接:
https://api.instagram.com/v1/users/3/followed-by?access_token=xxxxxxxxx.xxxxxxxxxxxxxxxxxxxx并显示如下结果
{
"data": [{
"username": "meeker",
"first_name": "Tom",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_6623_75sq.jpg",
"id": "6623",
"last_name": "Meeker"
},
{
"username": "Mark",
"first_name": "Mark",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_29648_75sq_1294520029.jpg",
"id": "29648",
"last_name": "Shin"
},
{
"username": "nancy",
"first_name": "Nancy",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_13096_75sq_1286441317.jpg",
"id": "13096",
"last_name": "Smith"
}]
}我如何计算有多少个,并将其放在一个var中,比如:
<? echo "You are been follow by ".$followers." users!"; ?>显示:你被3个用户关注!
发布于 2013-04-18 18:31:48
您需要使用json_decode来解码JSON响应,然后访问结果对象的数据属性(“follower”对象的数组),并对其进行计数:
$json = '{
"data": [{
"username": "meeker",
"first_name": "Tom",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_6623_75sq.jpg",
"id": "6623",
"last_name": "Meeker"
},
{
"username": "Mark",
"first_name": "Mark",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_29648_75sq_1294520029.jpg",
"id": "29648",
"last_name": "Shin"
},
{
"username": "nancy",
"first_name": "Nancy",
"profile_picture": "http://distillery.s3.amazonaws.com/profiles/profile_13096_75sq_1286441317.jpg",
"id": "13096",
"last_name": "Smith"
}]
}';
$json = json_decode($json);
echo "You have " .count($json->data) ." followers"或
$json = json_decode($json,true);
echo "You have " .count($json['data']) ." followers"发布于 2013-04-18 18:28:28
你得到的是一个json字符串,你需要使用json_decode解码它。
$data = json_decode($string,true);
$followers = count($data['data']);CodePad Demo。
发布于 2013-04-18 18:28:07
使用json_decode()从JSON创建一个PHP数组。然后,您可以简单地对其执行count():
$jsonData = json_decode($yourAPIResult);
echo count($jsonData->data);但是,请注意,您可能应该设置一些错误处理,以防API没有返回正确的JSON字符串。所以像这样的东西可能更好:
if (is_null($jsonData) || !property_exists($jsonData, 'data')) {
echo '?';
} else {
echo count($jsonData->data);
}https://stackoverflow.com/questions/16080451
复制相似问题