从 Twitter api 响应中获取提及总数

我正在使用基本搜索 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; 

当我 echo $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] 字段来获取计数


炎炎设计
浏览 85回答 1
1回答

慕容708150

这里有一些语法错误,并且缺少 的定义i,但根本问题是您试图计算错误的东西。如果您print_r($string)在代码末尾,您将看到它返回一个包含 2 个项目 -[statuses] => Array和 的数组[search_metadata] => Array。所以 2 是脚本中所写的正确输出。相反,您可以做的是计算状态数组本身。foreach($string["statuses"] as $array){&nbsp; &nbsp; $i++;}您可以做的另一件事是查看数组[search_metadata],其中包含结果的计数:&nbsp; &nbsp;[search_metadata] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [completed_in] => 0.161&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [max_id] => 1293225170983772160&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [max_id_str] => 1293225170983772160&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [next_results] => ?max_id=1293218662854402059&q=elrond&count=20&include_entities=1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [query] => elrond&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [refresh_url] => ?since_id=1293225170983772160&q=elrond&include_entities=1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [count] => 20&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [since_id] => 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [since_id_str] => 0&nbsp; &nbsp; &nbsp; &nbsp; )虽然,这两者实际上都会返回推文的数量,与您请求的数量相匹配count=20...因此,如果您想对关键字进行计数,您必须决定要对每个响应推文中的哪些字段进行计数from,然后迭代每个字符串中的这些条目。
打开App,查看更多内容
随时随地看视频慕课网APP