如何为玩家提供唯一的号码
我正在制作一个脚本,当玩家计数为 4 时,我将给出玩家编号。现在我有一个玩家表,我将使用玩家编号更新该表,但我似乎无法同时适应唯一编号生成和更新表一起循环...在脚本的这种情况下,我会给所有玩家编号 3...
到目前为止我所得到的是:
<?PHP
include '../config.php';
$con = mysql_connect($hostip, $mysqluser, $mysqlpass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($mysqldatabase, $con);
$gameid = '08e893ac1c4446758ee44423c173c5aa';
/////////////////////////// mysq connect end
$sql=mysql_query("SELECT DISTINCT username FROM table");
$pn = array();
while ( count($pn) < 4 ) {
$random = mt_rand(1,4);
if ( !in_array($random,$pn) ) {
$pn[] = $random;
$rr = $random;
while ($rowx = mysql_fetch_array($sql)) {
echo $rr.' '.$rowx['username'].' ';
}
}
}
print_r($pn); ?>
输出是
3 user1 3 user2 3 user3 3 user4 Array ( [0] => 3 [1] => 1 [2] => 4 [3] => 2 )
我猜它只得到第一个数字...我已经尝试过其他方法也是如此,但这似乎是寻找解决方案的更好方法。
//编辑解决方案
$randoms = range(1, 4);
shuffle($randoms);
while ($rowx = mysql_fetch_array($sql)){
$random = array_shift($randoms);
echo $random.' '.$rowx['username'].' ';
}
I'm making a script where I will be giving player numbers when the player count is 4. Now I have a player table that I will update with the player numbers but I can't seem to fit both unique number generation and updating the table loops together... In this condition of the script I would be giving all the players number 3...
What I have so far is this:
<?PHP
include '../config.php';
$con = mysql_connect($hostip, $mysqluser, $mysqlpass);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($mysqldatabase, $con);
$gameid = '08e893ac1c4446758ee44423c173c5aa';
/////////////////////////// mysq connect end
$sql=mysql_query("SELECT DISTINCT username FROM table");
$pn = array();
while ( count($pn) < 4 ) {
$random = mt_rand(1,4);
if ( !in_array($random,$pn) ) {
$pn[] = $random;
$rr = $random;
while ($rowx = mysql_fetch_array($sql)) {
echo $rr.' '.$rowx['username'].' ';
}
}
}
print_r($pn); ?>
Output is
3 user1 3 user2 3 user3 3 user4 Array ( [0] => 3 [1] => 1 [2] => 4 [3] => 2 )
I guess it only gets the first number... I've tried it other ways too but this seemed to be a better one to present to find a solution.
//EDIT SOLUTION
$randoms = range(1, 4);
shuffle($randoms);
while ($rowx = mysql_fetch_array($sql)){
$random = array_shift($randoms);
echo $random.' '.$rowx['username'].' ';
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要在循环中调用 mt_rand,提前生成一个随机列表,然后在需要时选择数字:
don't call mt_rand in a loop, generate a random list in advance and just pick the number when you need it: