4

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

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

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

echo $items[$result];

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

4

6 回答 6

8

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

$result = $items[ rand(1, 100) > 40 ? 1 : 0 ];
于 2012-06-21T13:58:13.177 回答
4
$val = rand(1,100);
if($val <= 40)
  return $items[0]; 
else 
  return $items[1];
于 2012-06-21T13:58:03.357 回答
3

只需使用普通rand方法:

if (rand(1,10) <= 4) {
    $result = $items[0];
} else {
    $result = $items[1];
}
于 2012-06-21T13:58:06.513 回答
3
if(rand(0, 100) <= 40) {
    # Item one
} else {
    # Item two
}
于 2012-06-21T13:58:44.370 回答
1

关于什么 ?

$rand = mt_rand(1, 10);
echo (($rand > 4) ? 'item2' : 'item1');
于 2012-06-21T14:01:47.427 回答
0
$index = rand(1,10) <= 4 ? 0 : 1;
echo $items[$index];
于 2012-06-21T13:59:02.537 回答