在我的脚本中,我想在一定的时间内运行某些代码,我查看了StackOverflow,发现了下面的代码。它33%的时间都在运行代码,我需要修改什么才能使它分别在55%和70%的时间运行?
$max = 27;
for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
call_function_here();
}
}
最简单的方法是使用随机数生成器,并测试其结果是否小于(或大于)您的目标量。
function percentChance($chance){
// Notice we go from 0-99 - therefore a 100% $chance is always larger
$randPercent = mt_rand(0,99);
return $chance > $randPercent;
}
...
if(percentChance(30)){
// 30% of page loads will enter this block
}
if(percentChance(100)){
// All page loads will enter this block
}
if(percentChance(0)){
// No chance this block will ever be entered
}
由于所选金额必须是常量,因此可以执行以下操作:
$max = 27;
$num_selections = round(27 * (55 / 100));
$keys = array_rand($max, $num_selections);
for ($keys as $key) {
// Do something with the chosen key
}