兰德();排除并已经随机生成的数字..?
我有一个函数可以从表中调用与用户关联的用户。然后该函数使用 rand();函数从数组中选择 5 个随机选择的用户 ID!...
如果用户没有很多关联用户但高于最小值(如果低于 5,则仅按原样返回数组),那么它会给出不好的结果,因为重复随机数...
如何克服这个问题或从下一个随机数()中排除先前选择的随机数;函数调用。
这是执行该工作的代码部分。请记住,这必须非常高效,因为该脚本到处都在使用。
$size = sizeof($users)-1;
$nusers[0] = $users[rand(0,$size)];
$nusers[1] = $users[rand(0,$size)];
$nusers[2] = $users[rand(0,$size)];
$nusers[3] = $users[rand(0,$size)];
$nusers[4] = $users[rand(0,$size)];
return $nusers;
提前致谢! 斯特凡
I have a function which calls a users associated users from a table. The function then uses the rand(); function to chose from the array 5 randomly selected userID's however!...
In the case where a user doesnt have many associated users but above the min (if below the 5 it just returns the array as it is) then it gives bad results due to repeat rand numbers...
How can overcome this or exclude a previously selected rand number from the next rand(); function call.
Here is the section of code doing the work. Bare in mind this must be highly efficient as this script is used everywhere.
$size = sizeof($users)-1;
$nusers[0] = $users[rand(0,$size)];
$nusers[1] = $users[rand(0,$size)];
$nusers[2] = $users[rand(0,$size)];
$nusers[3] = $users[rand(0,$size)];
$nusers[4] = $users[rand(0,$size)];
return $nusers;
Thanks in advance!
Stefan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法是使用
array_rand()
:PS:阅读此内容 了解为什么应该使用
mt_rand()
而不是rand()
。The simplest way is to use
array_rand()
:PS: Read this to know why you should use
mt_rand()
instead ofrand()
.如果您只想打乱数组项,请使用
shuffle
:请注意
shuffle
需要通过引用传递。所以你需要传递一个然后被打乱的变量。If you just want to shuffle your array items, use
shuffle
:Note that
shuffle
requires pass by reference. So you need to pass a variable that’s is then shuffled.