php percentage chance

后端 未结 4 1096
说谎
说谎 2021-01-14 21:05

This is really more a question of approach, but I\'m presenting it in php.

Suppose we had a list of four percentages that a give event will occur on iteration.

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 21:13

    $arr = array('walk the dog'=>25,'read the paper'=>25,'listen to music'=>50);
    $rand = rand(1,100);
    $sum = 0;
    $action = '';
    
    foreach ($arr as $k => $v) {
        $sum .= $k;
        if ($sum <= $k)
            $action = $v;
    }
    

    Removed those with a key value of zero, and multiplied the key-value with 100 to make it more readable.

提交回复
热议问题