如何使用php以随机方式显示mysql的输出
问题描述:
I want to display output from mysql using php in random manner. by default whole array will be displayed sequentially.
echo "<table border='1'>
</tr>
<tr>
<th>User ID</th>
<th>User </th>
<th>Site </th>
<th>IP Address</th>
<th>Date</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['userID'] . "</td>";
echo "<td>" . $row['user_name'] . "</td>";
echo "<td>" . $row['site_name'] . "</td>";
echo "<td>" . $row['ip_address'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
echo "</tr>";
}
echo "</table>";
I want to output to be displayed randomly on each access.
i.e. row1 is displayed on first access on top of output. row10 is displayed on 2nd access on top of output. row13 is displayed on 3rd access on top of output.
thanks for suggestions and help.
我想以随机方式使用php显示mysql的输出。 默认情况下,整个数组将按顺序显示。 p>
echo“&lt; table border ='1'&gt;
&lt; / tr&gt;
&lt; tr&gt;
&lt; ;&gt;用户ID&lt; / th&gt;
&lt; th&gt;用户&lt; / th&gt;
&lt; th&gt;站点&lt; / th&gt;
&lt; th&gt; IP地址&lt; / th&gt;
&lt; th&gt;日期&lt; / th&n;
&lt; / tr&gt;“;
而($ row = mysqli_fetch_array($ result))
{
echo”&lt; tr&gt;“;
echo”&lt; td&gt;“ 。 $ row ['userID']。 “&lt; / td&gt;”;
echo“&lt; td&gt;” 。 $ row ['user_name']。 “&lt; / td&gt;”;
echo“&lt; td&gt;” 。 $ row ['site_name']。 “&lt; / td&gt;”;
echo“&lt; td&gt;” 。 $ row ['ip_address']。 “&lt; / td&gt;”;
echo“&lt; td&gt;” 。 $ row ['date']。 “&lt; / td&gt;”;
echo“&lt; / tr&gt;”;
}
echo“&lt; / table&gt;”;
code> pre>
I 想要输出以便在每次访问时随机显示。 p>
即在输出顶部的第一次访问时显示
row1。
nrow10显示在输出顶部的第二次访问上。
row13是 在输出顶部的第3次访问中显示。 p>
感谢您的建议和帮助。 p>
div>
答
you can use mysql rand()
for the purpose:
For eg:
SELECT * FROM myTable ORDER BY RAND();
答
You can use ORDER BY RAND() in your sql query
SELECT * FROM `table_name` ORDER BY RAND()
You can also shuffle your php array using shuffle($my_array);
You can also use
function shuffle_assoc($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[$key] = $list[$key];
}
return $random;
}