2
您好我有一個MySQL列表,每列下面有14列和1到10個行之間的行。我希望從每列中隨機調用一個條目來隨機組合條目。鑑於一個列可能只有一個條目在其下面,那麼每次都會調用該條目...如果它只有2個條目,那麼它會調用2中的1個,如果它有10個,那麼它會調用10箇中的1個等等都是隨機的!隨機句子使用PHP和MySQL
我用這個suggestion通過Matthew McGovern和它的作品很好,但它僅調用跨列的幾個條目,並從每個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()'](http://php.net/array-rand)更好。 – BlitZ
而不是'$ rows = array();'?兩種方法都是一樣的嗎? – Joe
*強制性的:*'mysql_ *'函數將[在PHP 5.5中棄用](http://php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated)。不建議編寫新代碼,因爲它將來會被刪除。取而代之的是,無論是[庫MySQLi](http://php.net/manual/en/book.mysqli.php)或[PDO](http://php.net/manual/en/book.pdo.php)和[是一個更好的PHP開發人員](http://jason.pureconcepts.net/2012/08/better-php-developer/)。 –