我想知道如何计算有多少人关注Instagram中的某个人并将数字放在var中,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位用户!
答案 0 :(得分:3)
您需要使用json_decode来解码JSON响应,然后访问结果对象的数据属性(一组'跟随者'对象),并计算:
$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"
答案 1 :(得分:1)
您将获得json字符串,需要使用json_decode解码它。
$data = json_decode($string,true);
$followers = count($data['data']);
答案 2 :(得分:0)
使用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);
}
答案 3 :(得分:0)
您需要使用json_decode()
来返回PHP数组。然后,您需要做的就是使用'data'键count()
数组中的所有值。
答案 4 :(得分:0)
您可以使用json_decode
$array = json_decode($str);
然后给
echo count($array);
它将提供用户总数
答案 5 :(得分:0)
计算返回为JSON的条目的简单方法
echo count(json_decode($followers);