从 Twitter api 回复中获取提及总数

Get total count of mentions from a twitter api response

我正在使用基本搜索 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),您会看到它是 return 包含 2 个项目的数组 - [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
        )

虽然,这两个实际上 return 推文的数量,与您请求的数量相匹配 count=20...所以如果您想计算关键字,您必须决定您希望从每个响应推文中的哪些字段对其进行计数,然后遍历每个字符串中的这些条目。