Help us understand the problem. What is going on with this article?

PHPでの簡単な抽選方法

More than 3 years have passed since last update.

ちょっとした抽選をしたい時。

1等が3%の確率、2等が5%の確率、3等が10%の確率、4等が82%の確率で出す場合。

valueが確率となるので合計100が理想ですが、100じゃなくても動きます。

    $entries = array(
        "1"    => 3,
        "2"    => 5,
        "3"    => 10,
        "4"  => 82,
    );

    $result_key = $this->array_lottery($entries);

    $data = [];
    switch($result_key){
        case 1:
            $data['rank'] = "1等賞"; 
            $data['prize'] = "現金200,000円"; 
            break;
        case 2:
            $data['rank'] = "2等賞"; 
            $data['prize'] = "現金50,000円"; 
            break;
        case 3:
            $data['rank'] = "3等賞"; 
            $data['prize'] = "現金3,000円"; 
            break;
        case 4:
            $data['rank'] = "4等賞"; 
            $data['prize'] = "あめ玉"; 
            break;
    }

    echo "あなたは" . data['rank'] . "です。" . $data['prize'] . "ゲットです!";
    public function array_lottery($entries){
        $sum  = array_sum($entries);
        $rand = rand(1, $sum);
        foreach($entries as $key => $weight){
            if (($sum -= $weight) < $rand){
                return $key;
            }
        }
    }

賞品の個数が決まってない場合の簡単な方法です。
個数が決まっている場合はもう少し複雑なロジックが必要。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした