问题描述
我正在使用基本的搜索twitter api,我想获取响应中提到的特定单词的总数。这就是我的api调用的样子-
$url = "https://api.twitter.com/1.1/search/tweets.json";
$requestMethod = "GET";
// Keyword to search
$getfield = '?q=elrond&count=20';
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)->buildOauth($url,$requestMethod)->performRequest(),$assoc = TRUE);
if(array_key_exists("errors",$string)) {echo "<h3>Sorry,there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}
echo "<pre>";
print_r($string);
echo "</pre>";
foreach($string as $array){
$i++;
}
echo $i;
当我回显$ i时,我得到一个2的计数,但是如果查看实际响应,则它们超过100次提及该关键字。我将使用哪种方法来计算关键字在响应中的次数?
这是我得到的示例回复-
[1] => Array
(
[created_at] => Tue Aug 11 16:04:39 +0000 2020
[id] => 1293216771244261381
[id_str] => 1293216771244261381
[text] => @Meter_IO @ElrondNetwork You know just the right partnership,with elrond network,you are certainly in for something big. ?
[truncated] =>
[entities]
我将在[text]字段中搜索计数
解决方法
您在这里遇到了一些语法错误,并且缺少i
的定义,但是根本的问题是您正在尝试计算错误的内容。
如果您在代码末尾print_r($string)
,则将看到它返回的数组包含两个项:[statuses] => Array
和[search_metadata] => Array
。所以2是您编写的脚本的正确输出。
您可以做的是计算状态数组本身。
foreach($string["statuses"] as $array){
$i++;
}
您可以做的另一件事是查看[search_metadata]
数组,其中包含结果计数:
[search_metadata] => Array
(
[completed_in] => 0.161
[max_id] => 1293225170983772160
[max_id_str] => 1293225170983772160
[next_results] => ?max_id=1293218662854402059&q=elrond&count=20&include_entities=1
[query] => elrond
[refresh_url] => ?since_id=1293225170983772160&q=elrond&include_entities=1
[count] => 20
[since_id] => 0
[since_id_str] => 0
)
尽管这两个函数实际上都返回Tweets的数量,这些数量与您请求的count=20
数量......因此,如果要计算关键字,则必须决定其中的哪些字段您想从中计算每个响应的Tweet,然后遍历每个字符串中的那些条目。