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

问题描述 投票:0回答:2

我有一个事件列表,其中包含用户输入的关键字。在每天结束时,我聚合所有这些并使用以下代码计算每个关键字的出现次数(请注意我也计算为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天获得数据。

为此,我将在我的聚合表中检索数据,其中时间戳在此日期范围之间。并且我将返回所有行以及它们的出现次数(PER DAY)。

现在很明显,昨天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
php
2个回答
1
投票

在你的mysql上尝试这个查询:

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

1
投票

在PHP中

$total = array()

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

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

© www.soinside.com 2019 - 2024. All rights reserved.