views:

153

answers:

2

I have banners advertising with number of views, like CPM system. And for example :

i have 3 banner:
banner1 with 20.000 nr of views
banner2 with 10.000 nr of views
banner3 with 5.000 nr of views

and on my website the banner must to appear in this position (when the page is reloaded) :

banner1 banner2 banner1 banner2 banner3

if the number of views is higher then the probability of apparition is higher

how can i do this in php?

Thanks a lot for helping :)

+2  A: 

Here's a php way to do it

I'm imagining your array will look something like this...

$banners = array(

    array (
        'name' => 'banner1',
        'views' => 20
    ),
    array (
        'name' => 'banner2',
        'views' => 10
    ),
    array (
        'name' => 'banner3',
        'views' => 5
    )
);

This function basically loops through the banners and however many views a banner has, that many items of its array index are added to an array. Then a random one is chosen. Items with more views have a better chance of being chosen.

function getWeightedRandom( $array ) {

    $universe_array = array();

    foreach ( $array as $k => $b ) {
        $universe += $b['views'];
        $universe_array = array_pad( $universe_array, $universe, $k );
}

    $rand = mt_rand( 0, count( $universe_array ) -1 );
    return $array[ $universe_array[ $rand ] ];

}


$r = getWeightedRandom($banners);
print_r($r);

A simple mysql option is:

select * from banners order by rand() * views desc limit 1

banners with more views will have a higher chance of being the top result

Galen
-1, That SQL query will always return the banner with the most views.
Alix Axel
Actually it wont.
Galen
@Galen: You're right sorry, switched my vote.
Alix Axel
A: 

First of all, your system is just... stupid. It perpetuates banners with lots of views while newly created banners with 0 or few views will never get a chance to be picked and thus will never be actually seen...

That being said, if you have an array that looks like this:

$banners = array
(
    'banner1' => 1,
    'banner2' => 2,
    'banner3' => 4,
    'banner4' => 8,
    'banner5' => 16,
);

You can use a function like this one to weightily pick one banner:

function Probability($data)
{
    if (is_array($data) === true) {
        $result = 0;
        $probability = mt_rand(1, array_sum($data));

        foreach ($data as $key => $value) {
            $result += $value;

            if ($result >= $probability) {
                return $key;
            }
        }
    }

    return false;
}

Usage (test it @ CodePad.org or @ IDEOne):

echo Probability($banners); // banner5

Sample from 100 executions:

Array
(
    [banner5] => 41
    [banner4] => 38
    [banner3] => 10
    [banner2] => 8
    [banner1] => 3
)
Alix Axel