Udělal bych to přes překladovou tabulku:
PHP kód:
$draw = new Weighted_Draw;
echo $draw->choose();
class Weighted_Draw {
protected $weights = array(
1 => 'Choice 1, 60%',
61 => 'Choice 2, 30%',
91 => 'Choice 3, 10%'
);
protected $draw;
protected $choice;
public function __construct() {
krsort($this->weights);
}
public function choose() {
return $this->draw()
->translate()
->lastChoice();
}
public function lastChoice() {
return $this->choice;
}
protected function draw() {
$this->draw = rand(1, 100);
return $this;
}
protected function translate() {
$this->choice = NULL;
reset($this->weights);
foreach($this->weights AS $lowerLimit => $choice) {
if($lowerLimit <= $this->draw) {
$this->choice = $choice;
break;
}
}
return $this;
}
}