Probability banner

I have banner ads with the number of views, for example, the 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 should appear in this position (when the page is reloaded):

banner1 banner2 banner1 banner2 banner3

if the number of views is greater than the probability of occurrence of the phenomenon is higher

how can i do this in php?

+4
source share
2 answers

First of all, your system is just ... stupid . It perpetuates banners with a large number of views, while newly created banners with 0 or more views will never be able to be selected and, therefore, will never actually be visible ...

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 to weigh 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 

Example of 100 executions:

 Array ( [banner5] => 41 [banner4] => 38 [banner3] => 10 [banner2] => 8 [banner1] => 3 ) 
+2
source

Here's the php way to do it

I imagine that 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 goes through the banners, and as many of them look at the banner, many elements of the array index are added to the array. Then random is selected. Items with more views are more likely to be selected.

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

Simple mysql option:

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

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

+2
source

Source: https://habr.com/ru/post/1308564/


All Articles