再次计算PHP中字符串的出现次数

时间:2019-03-15 10:17:11

标签: php

我有一个事件列表,其中包含用户输入的关键字。在每天结束时,我将所有这些汇总在一起,并使用以下代码计算每个关键字的出现次数(请注意,我也计算NULL):

$nameArray = [];
foreach ($eventsYesterday as $event) {
   if (empty($event->name)) {
       $nameNullCounter++;
   } else {
       array_push($nameArray, strtolower($event->name));
   }
}
$countedNameArray = array_count_values($nameArray);

这时,我有一个结果集,其中包含每个关键字的计数。

然后,每天晚上(午夜之后)将它们保存到我的聚合表中,如下所示:

//If there has been more than 0 NULL searches on name, insert that too with its counter
            if ($nameNullCounter > 0) {
                $obj = new stdClass();
                $obj->name = NULL;
                $obj->amount_name = $nameNullCounter;
                $obj->region_name = $regionName;
                $time = strtotime("-1 day", time());
                $yesterday = date("Y-m-d", $time);
                $obj->timestamp = $yesterday;      //Since this is executed after midnight, we need to insert the date of yesterday
                $this->searchOrganisationNameLocAggr_model->add($obj);
            }
            //Insert for each occurence in the searchOrganisationNameLocAggr model
            foreach ($countedNameArray as $key => $value) {
                $obj = new stdClass();
                $obj->name = $key;
                $obj->amount_name = $value;
                $obj->region_name = $regionName;
                $time = strtotime("-1 day", time());
                $yesterday = date("Y-m-d", $time);
                $obj->timestamp = $yesterday;      //Since this is executed after midnight, we need to insert the date of yesterday
                $this->searchOrganisationNameLocAggr_model->add($obj);
            }

当我的用户查看统计信息时,我为他们提供了选择日期范围的选项。因此,例如,如果他们选择“上周”,则他们将从昨天到昨天(7天)获取数据。

为此,我将在聚合表中检索时间戳介于该日期范围之间的数据。然后,我将所有行及其发生的次数(每天)返回。

现在很明显,昨天已被搜索过5次的关键字也可以在3天前被搜索两次。我想对所有这些关键字名称进行“重新计数”,然后将它们的总数加起来。

一个例子是,数据是这样的:

name: NULL
amount_name: 3
date: 2019-03-13 00:00:00

name: "test"
amount_name: 1
date: 2019-03-13 00:00:00

name: NULL
amount_name: 3
date: 2019-03-14 00:00:00

name: "test"
amount_name: 5
date: 2019-03-14 00:00:00

name: "a"
amount_name: 3
date: 2019-03-14 00:00:00

我希望结果是:

name: NULL
amount_name: 6

name: "test"
amount_name: 6

name: "a"
amount_name: 3

2 个答案:

答案 0 :(得分:1)

在您的mysql上尝试以下查询:

SELECT SUM(amount_name) FROM table WHERE date between(start_date, end_date) GROUP BY name

答案 1 :(得分:1)

在php中

$total = array()

foreach($results as $result){
   if (!isset($total[$result->name]) $total[$result->name] = 0
   $total[$result->name]+=$result->amount_name
}

但实际上,mySql解决方案更好