【问题标题】:Splitting website traffic by percentage按百分比拆分网站流量
【发布时间】:2014-06-26 15:56:48
【问题描述】:

我需要根据指定的百分比将流量分配到多个来源。我想我需要一个这样的日志表:

表:

+--------+------+----------------------+
| Source | hits | allocated percentage |
+--------+------+----------------------+
| path1  |  50  | 50                   |
| path2  |  40  | 40                   |
| path3  |  10  | 10                   |
+--------+------+----------------------+

我认为逻辑需要遍历所有路径并计算当前百分比,然后确定哪个距离“分配的百分比”最远,然后更新表hits=hits+1。我在最后一个比较部分遇到了麻烦。

$overall_hits = $db->getall('Select sum(total_hits) from table');

$source = $db->getall('Select * from table');
foreach($source as $row){

    $current_percentage = ($row['total_hits']/$overall_hits)*100;

    //how should I compare? what if they are equal?
    if($current_percentage < $row['allocated_percentaged'])
    {      

    $chosen_path = $row['source'];
    $db->sql("Update table set total_hits=total_hits+1 where source='".$chosen_path."'");
    break;    

    }else{

    continue;

    }

}

我是否走在正确的轨道上?

【问题讨论】:

  • 这不是您实际代码的一部分,是吗? foreach(source as row){ --- 称之为
  • 你需要的是一个 A/B 测试框架:phpabtest.com
  • 是错字吗?因为fetchAll() 方法中的字符串缺少单引号
  • 为什么需要确定哪一个距离“分配百分比”最远?随机生成器可能并不完美,但从长远来看,您会自动获得百分比。
  • 同上。只需使用随机数生成器;这比试图确保 40% 真正意味着 40% 更容易,也可能更准确。

标签: php mysql loops foreach


【解决方案1】:

假设我了解您要执行的操作,您可以在 SQL 中执行所有逻辑检查。

以以下数据为例:

CREATE TABLE t (
  source TEXT,
  hits INT,
  percentage INT
  );

INSERT INTO t (source, hits, percentage)
VALUES 
  ('path1', 41, 50), 
  ('path2', 27, 40), 
  ('path3', 3, 10)

您可以简单地对整个表运行查询,以计算每个路径的百分比:

SELECT 
  source, 
  hits, 
  percentage, 
  (hits / percentage) * 100
    AS current 
  FROM t
  ORDER BY current ASC;

这将为您提供以下结果

SOURCE  HITS    PERCENTAGE  CURRENT
path1   3       10              30
path2   27      40              67.5
path3   41      50              82

然后,您可以简单地将LIMIT 1 添加到查询的末尾,仅获得 1 个结果。这将为您提供hits : allocated 比率最少的路径。

SOURCE  HITS    PERCENTAGE  CURRENT
path1   3       10              30

您可以在 SQLFiddle here 上看到它的实际效果。

【讨论】:

  • 谢谢我没有想到用 mysql 来做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 2019-08-07
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
相关资源
最近更新 更多