你不能同时拥有所有三个。这是不可能的。
前两个,当然。但最后一个只能是一个数字,这就是剩下的。
// vote 1
$vote_limit = $v_cnt;
$vote_1 = mt_rand(0, $vote_limit);
// vote 2
$vote_limit = $v_cnt - $vote_1;
$vote_2 = mt_rand(0, $vote_limit);
// vote 3
$vote_3 = $v_cnt - ($vote_1 + $vote_2);
https://3v4l.org/2C2bu
我也不确定你希望这条线做什么:if($vote_limit < 0){ $vote_limit = 0;}。
$vote_limit 不能为负数,因为您有随机数的限制。
我看到您已经添加了一个拥有唯一号码的请求。
我创建了一个新代码,它输出的 $n_votes 投票都是唯一的,没有一个是负数,并且都在 0 和 $v_cnt 之间。
$v_cnt = 100;
$n_votes = 3;
$numbers = range(0,$v_cnt); // create array of 0->100
shuffle($numbers); // shuffle the array
$votes = array_fill(0, $n_votes-1, 1); // create an array that will NOT exit loop below.
// Array_fill returns [1,1,1] which does not match the requirements so the loop starts
//Loop until all values in votes are unique and none is negative
while(count(array_unique($votes)) != $n_votes || $votes[$n_votes-1]<1){
// Take two consecutive numbers of random place in the array
$votes = array_slice($numbers, mt_rand(0, $v_cnt-$n_votes+1),$n_votes-1);
// Count what the last item should be
$votes[] = $v_cnt - array_sum($votes);
}
echo array_sum($votes) . "\n";
Var_dump($votes);
https://3v4l.org/2h7DB
看起来很有趣,如果我在代码中包含 $i,我们可以看到循环中需要多少次尝试才能创建唯一数组。 https://3v4l.org/mPae5
请记住,此代码对与投票数相反的最大限制非常敏感。
如果您的 $v_cnt 相对较低而 $n_votes 较高,则可能永远找不到所需的数字。
只需尝试在最新链接中将 $n_votes 设置为 5,您可以看到 $i 数字可以是 100+(这意味着需要超过 100 个循环才能获得正确的数字集)。