gpt4 book ai didi

php - 调用百分比的随机函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:55 24 4
gpt4 key购买 nike

我想不通。

我需要一个解决方案来调用一个随机函数,因为它是百分比。

例。脚本调用 subscriptions() 的可能性为 10%,系统调用函数“specialitems()”的可能性为 3%。

我被困在这个问题上,所以我希望有人能帮助我解决这个脑残问题。

<?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(){}

}
?>

最佳答案

试试这个:

$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();

百分比加起来不应超过 100。如果总和低于 100,则剩余百分比“什么都不做”。

关于php - 调用百分比的随机函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13891480/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com