【发布时间】:2013-07-10 02:28:26
【问题描述】:
您好,我有一个 MySQL 表,它有 14 列,每列下方的行中有 1 到 10 个条目。我希望从每一列中随机调用一个条目以随机组合条目。假设一列下面可能只有一个条目,那么每次都会调用该条目......如果它只有 2 个条目,那么它将调用 2 个条目中的 1 个,如果它有 10 个,那么它将调用 10 个条目中的 1 个等等都是随机的!
我通过Matthew McGovern 使用了这个suggestion,它工作得很好,但它只调用了跨列的几个条目,而不是14 个中的每一个。
我可以修改代码以使其各调用一个吗?
他的代码:
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "yyy") or die (mysql_error());
// Select database
mysql_select_db("zzz") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Users";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Array to hold all data
$rows = array();
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// add row to array.
$rows[] = $row;
}
// Close the database connection
mysql_close();
// Max rand number
$max = count($rows) - 1;
// print out random combination of data.
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][3] . " "
. $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " "
. $rows[rand(0, $max)][4] . " " . $rows[rand(0, $max)][5];
?>
【问题讨论】:
-
array_rand()更好。 -
而不是
$rows = array();?两种方式都一样吗? -
强制:
mysql_*函数将是 deprecated in PHP 5.5。不建议编写新代码,因为它会在未来被删除。相反,MySQLi 或 PDO 和 be a better PHP Developer。