Question

I need to split up traffic to multiple sources based on an assigned percentage. I figure I need a log table like this:

Table:

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

I figure the logic needs to loop through all the paths and calculate the current percentage and then determine which one is furthest from the "allocated percentage" and then update the table hits=hits+1. I'm having trouble with the last compare part.

$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;

    }

}

Am I even on the right track here?

Was it helpful?

Solution

Presuming I understand what you're trying to do, you can do all of the logic checks in your SQL.

Using the following data as an example:

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)

You can simply run a query against the entire table, to calculate what percentage each of the paths is at:

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

Which will give you the following results

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

You can then simply add LIMIT 1 to the end of your query, to only obtain 1 result. This will give you the path with the lowest number of hits : allocated ratio.

SOURCE  HITS    PERCENTAGE  CURRENT
path1   3       10              30

You can see it in action on SQLFiddle here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top