在百分比上调用随机函数?

Ang*_*kin 5 php random

我无法弄清楚这一点.

我需要一个解决方案来调用随机函数的百分比.

防爆.脚本调用subscriptions()的可能性为10%,系统调用函数"specialitems()"的概率为3%.

我被困在这里,所以我希望有人可以帮我这个brainkiller.

<?php
   class RandomGifts {
   public $chances = '';

   public function __construct($user) {
          $this->user = $user;

          //Find percent for each function
          $this->chances = array( 
                 'subscriptions' => 10, // 10%
                 'specialitems'  => 3,  //  5%
                 'normalitems'   => 30, // 40%
                 'fuser'         => 50, // 70%
                 'giftcards'     => 7,  //  7%
          );

 //This should call the function which has been calculated.
 self::callFunction(?);

 }

   public function subscriptions(){}
   public function specialitems(){}
   public function normalitems(){}
   public function fuser(){}
   public function giftcards(){}

}
?>
Run Code Online (Sandbox Code Playgroud)

irr*_*ant 4

尝试这个:

$a = rand(1, 100);
$total = 0;
$f = '';
foreach($this->chances as $function => $percent) {
    $total += $percent;
    if($a <= $total) {
        $f = $function;
        break;
    }
}
if(!empty($f))
    $this->$f();
Run Code Online (Sandbox Code Playgroud)

百分比相加不应超过 100。如果总和低于 100,则剩余百分比“不执行任何操作”。