Jump to content

Not so rand()


TEENFRONT

Recommended Posts

Hey everyone

I have made my own custom banner manager script where i add campaigns etc and i have 1 file that serves the banner code and logs impressions and clicks etc.

Basically, my question is, how do i add more "weight" to a banner?

At the moment i use a mysql select rand() statement, and that randomley selects 1 of 2 banner codes and spits it out.

How would i make rand() not so random? :-) So say, its still a random display, but theres more chance of banner1 appearing than banner2?

Why i want to do this? Well i earn more with banner1 than banner2, but carnt not have banner2, so id rather give preference to banner1 say 70/30 display chance split?


Any tips?
Link to comment
https://forums.phpfreaks.com/topic/35680-not-so-rand/
Share on other sites

What I would do is create an array.
Have a field in your table called weight, and make it an int.
Banner1 would have weight 2, banner 2, weight 1.
Get all the banners from the table and put them in an array with their ID as the key and their weight as the value.

foreach($bannersListFromDB AS $bannerID => $weight){
  for($i=1; $i<=$weight; $i++){
    $banners[] = $bannerID;
  }
}
So you'll end up with this:
$banners[0] = '1';
$banners[1] = '1';
$banners[2] = '2';

Then shuffle the array and pick the first one, or use array_rand.
Link to comment
https://forums.phpfreaks.com/topic/35680-not-so-rand/#findComment-169028
Share on other sites

I would use the rand() function to generate numbers between 1 and 100, then depending on your criteria, display the proper banner. The following show one method:
[code]<?php
$n = 10000;
$banners = array(0,0);
for ($i=0;$i<$n;$i++) {
  $rnd = rand(1,100);
if ($rnd < 71) $banners[0]++;
else $banners[1]++;
}
for ($i=0;$i<count($banners);$i++)
echo "Banner $i was displayed <span style='color:red;font-weight:bold'>" . number_format(($banners[$i]/$n)*100,2) . '%</span> of the time<br>';
?>[/code]

If you execute the above script many times, you will see that the percent that a particular banner would be displayed is very close to what you're looking for.

Ken
Link to comment
https://forums.phpfreaks.com/topic/35680-not-so-rand/#findComment-169040
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.