I\'m working on building an ad banner rotation script based on impressions that displays ads evenly throughout the month. The calculations will be done each time the ad
Personally, I'd work out what percentage of impressions each ad has received compared to how many are paid for, and use that as the chance that it won't show up. Something like this:
$show = Array();
foreach($ads as $id=>$ad) {
$show[$id] = ceil((1-$ad['impressions']/$ad['paid'])*100);
}
$total = array_sum($show);
$rand = rand(1,$total);
$winner = -1;
do {$rand -= array_shift($show); $winner++;} while($rand && $show);
$ad_to_display = $ads[$winner];
For example, consider four ads, A, B, C and D. All of them have paid for 1,000 impressions, but so far A has been unlucky and gotten zero, while B and C both have had 500 impressions, and D has had 999.
This would mean $show
has these values for the ads:
A: ceil((1-0/1000)*100) = 100
B: ceil((1-500/1000)*100) = 50
C: ceil((1-500/1000)*100) = 50
D: ceil((1-999/1000)*100) = 1
$total
is therefore equal to 201.
$rand
can be any number from 1 to 201 inclusive. Let's say 141.
In this case, we begin our loop:
$rand -= 100
, now it's 41. 41 is truthy and we have ads remaining.$rand -= 50
, now it's -9. It has reached zero, so end the loop.The $winner
is 1, which is advert B.