根据给定的百分比在两个项目之间进行选择


Choose between two items based upon a given percentage

>我需要根据 40/60% 的比率显示数组中的两个项目之一。因此,40% 的时间,项目一显示,60% 的时间,项目二显示。

我现在有以下代码,它将在两者之间随机选择,但需要一种方法来添加百分比权重。

$items = array("item1","item2");
$result = array_rand($items, 1);
echo $items[$result];

任何帮助将不胜感激。谢谢!

这样的东西应该可以解决问题

$result = $items[ rand(1, 100) > 40 ? 1 : 0 ];
$val = rand(1,100);
if($val <= 40)
  return $items[0]; 
else 
  return $items[1];

只需使用正常的rand方法:

if (rand(1,10) <= 4) {
    $result = $items[0];
} else {
    $result = $items[1];
}
if(rand(0, 100) <= 40) {
    # Item one
} else {
    # Item two
}

怎么样?

$rand = mt_rand(1, 10);
echo (($rand > 4) ? 'item2' : 'item1');
$index = rand(1,10) <= 4 ? 0 : 1;
echo $items[$index];