如何使用PHP在MySQL上使用随机数据或随机数据?

时间:2015-07-09 08:09:00

标签: php mysql random xampp shuffle

你好我有这样的表:

员工

gs -dPDFX -dBATCH -dNOPAUSE -dNOOUTERSAVE -dUseCIEColor \
   -sProcessColorModel=DeviceCMYK -sDEVICE=pdfwrite \
   -sOutputFile=output-x1a.pdf PDFX_def.ps output.pdf

我用这个源代码制作随机数据:

EmployeeID  EmployeeName 
1234        Suho    
1235        Kai    
1236        Baekhyun    
1237        Lay  
1238        D.O      
1239        Chen
1240        Chanyeol
1241        Xiumin
1242        Sehun

随机抽取数据后,结果如下:

<?php

mysql_connect("localhost", "root", "1234") or die(mysql_error());
mysql_select_db("Employee") or die(mysql_error());

$employees = mysql_query("select p.*
from (select (@c := CHAR(ASCII(@c) + 1)) as c, EmployeeName
      from Employee cross join
           (select @c := 'A') params
      order by EmployeeId
     ) p order by rand();") 
or die(mysql_error());  

$letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$position = 0;
$position2 = 0;
$toomany = '';

while($row = mysql_fetch_array( $employees )) {
    echo "<DIV>" . $toomany.substr($letters, $position, 1) . " = " . $row['EmployeeName'] . " </div>";
      $position ++;
    if($position > 25) {
        $position = 0;
        $position2 ++;
        if($position2 > 25) { echo "We need to rethink this idea."; break; }
        $toomany = substr($letters, $position2, 1);
    }
}

?>

或者像这样:

A  = Sehun     
B  = Suho     
C  = Kai     
D  = D.O     
E  = Chen       
F  = Chanyeol
G  = Baekhyun
F  = Lay
H  = Xiumin

问题是我想随机传输这样的数据(从数据库开始,EmployeeID按字母顺序改变):

A  = Kai     
B  = Suho     
C  = Sehun    
D  = D.O     
E  = Chen       
F  = Xiumin
G  = Lay
F  = Chanyeol
H  = Baekhyun

进入这个数据,数据具有相同的值但具有不同的序列(只有他们的位置改变,不仅他们的名字被随机化):

A = Suho     
B = Kai    
C = Baekhyun    
D = Lay  
E = D.O      
F = Chen
G = Chanyeol
H = Xiumin
I = Sehun

或者像这样:

G = Chanyeol  
C = Baekhyun   
B = Kai  
D = Lay  
I = Sehun
E = D.O      
F = Chen
A = Suho
H = Xiumin

你知道问题出在哪里吗?谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

从数据库获取所有内容并将其保存到PHP数组中,然后应用其中一个随机PHP函数。 Shuffle更改了密钥,因此我在PHP.net网站上看​​到了someone who posted a nice function来保存索引:

<?php
    function shuffle_assoc(&$array) {
        $keys = array_keys($array);

        shuffle($keys);

        foreach($keys as $key) {
            $new[$key] = $array[$key];
        }

        $array = $new;

        return true;
    }
?>