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'].' ';
}
don't call mt_rand in a loop, generate a random list in advance and just pick the number when you need it:
$randoms = range(1, 4);
shuffle($randoms);
while(...) {
$random = array_shift($randoms);
精彩评论