选定的ID将选择行并随机化。但是,它可以随机化相同的元素。 例如: “我喜欢弹钢琴。” 我期待的输出被随机化为例如。 '像我一样弹钢琴' 但我收到的东西有时候变成'我钢琴般的钢琴就像钢琴' 这个词来自数据库(phpmyadmin)。如何使数据全部显示但不重复?
$strSQL = "SELECT * FROM sentences WHERE id
ORDER BY RAND() LIMIT 1;";
$x = rand(1,4);
echo "$x";
$y = rand(1,4);
echo "$y";
$z = rand(1,4);
echo "$z";
$c = rand(1,4);
echo "$c";
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
echo "<dt>Sentence:</dt><dd>" . $row["$x"] . " " . $row["$y"] . " " . $row["$z"] . " " . $row["$c"] ."</dd>";
}
答案 0 :(得分:1)
你可以这样做:
//create an array with numbers 1-4
$order = array(1,2,3,4);
//shuffle them in random order
shuffle($order);
$rs = mysql_query($strSQL);
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
// Write the data of the person
//Display all the array values from 0-3 (array index starts from 0)
echo "<dt>Sentence:</dt><dd>" . $row[$order[0]] . " " . $row[$order[1]] . " " . $row[$order[2]] . " " . $row[$order[3]] ."</dd>";
}
Please, don't use mysql_*
functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDO或MySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial。
答案 1 :(得分:1)
尝试使用shuffle()
功能。
$strSQL = "SELECT * FROM sentences WHERE id
ORDER BY RAND() LIMIT 1;";
// Loop the recordset $rs
while($row = mysql_fetch_array($rs)) {
shuffle($row);
// Write the data of the person
echo "<dt>Sentence:</dt><dd>" . implode(' ', $row) . "</dd>";
}
无关:mysql_*
自PHP 5.5起已被弃用,将来会被删除。请改用mysqli或PDO。