(Google website optimizer kind of) randomization in PHP (but smart, quick and slim)
Every time someone v开发者_运维知识库isits my site, I show one of three options (A, B, C). If the user likes the option, he clicks on it. I want to find a way to show the options that receive less clicks less frequently. What's the best way of doing this in PHP?
I am saving the clicks in MongoDB by simply adding a "vote" in an array:
$option[]='a';//one click on option A
$option[]='b';//one click on option B
$option[]='b';//another click on option B
try{
$m=new Mongo();
$c=$m->db->clicks;
$c->save($option);
$m->close();
}
catch(MongoConnectionException $e){ die('Error connecting to MongoDB server. ');}
catch(MongoException $e){ die('Error: '.$e->getMessage());}
This prints:
Array
(
[0] => a
[1] => b
[2] => b
)
Not sure if I understand your question correctly. But if I did, then the following is perhaps a rather naive, and perhaps even verbose way of doing what I think you want to do:
// assume the following fictional values,
// that is, the amount of clicks each option has received thusfar
$clicks = array(
'A' => 10,
'B' => 40,
'C' => 50
);
// what is the total amount of clicks?
$totalClicks = array_sum( $clicks );
// determine the lower bound percentages of the option clicks
$clickPercentageBounds = array(
'A' => 0,
'B' => ( ( $clicks[ 'A' ] + 1 ) / $totalClicks ) * 100,
'C' => ( ( $clicks[ 'A' ] + $clicks[ 'B' ] + 1 ) / $totalClicks ) * 100
);
// get random percentage
$rand = mt_rand( 0, 100 );
// determine what option to show, based on the percentage
$option = '';
switch( true )
{
case $rand < $clickPercentageBounds[ 'B' ]:
$option = 'A';
break;
case $rand < $clickPercentageBounds[ 'C' ]:
$option = 'B';
break;
default:
$option = 'C';
break;
}
var_dump( $option );
You CAN do it with PHP and a db, but you might prefer using Google Website Optimizer, I think it offers that option and works quite well.
精彩评论