我正在尝试改进我的switch语句以使其更随机。目前我正在尝试随机化个人资料。两个配置文件一次显示在另一个上面。这些配置文件以幻灯片形式显示,每2.5秒淡入淡出一次。我不希望在加载网页时同时显示相同的配置文件(在顶部和底部)。提前感谢您提供的任何输入。我创建了两个switch语句如下:
<div id="Slider">
<?php
$getSliderInfoQuery = "SELECT f_name, l_name, city, zipcode, pst.name as state_id, book_types, profile_photo, profile_url, prt.rating FROM book_readers ps left join book_states pst on pst.state_id = ps.state_id left join book_reviews prt on prt.user_id = ps.user_id WHERE promoted_reader = 1 ORDER BY ";
$pickRow = mt_rand(1, 6);
$pickRow = mt_rand(1, 6);
switch($pickRow) {
case 1:
$getSliderInfoQuery .= "l_name";
break;
case 2:
$getSliderInfoQuery .= "f_name";
break;
case 3:
$getSliderInfoQuery .= "city";
break;
case 4:
$getSliderInfoQuery .= "profile_photo";
break;
case 5:
$getSliderInfoQuery .= "l_name DESC";
break;
case 6:
$getSliderInfoQuery .= "city DESC";
break;
<div id="Slider2">
<?php
$getSliderInfoQuery = "SELECT f_name, l_name, city, zipcode, pst.name as state_id, book_types, profile_photo, profile_url, prt.rating FROM book_readers ps left join book_states pst on pst.state_id = ps.state_id left join book_reviews prt on prt.user_id = ps.user_id WHERE promoted_reader = 1 ORDER BY ";
$pickRow = mt_rand(1, 6);
switch($pickRow) {
case 1:
$getSliderInfoQuery .= "f_name";
break;
case 2:
$getSliderInfoQuery .= "l_name";
break;
case 3:
$getSliderInfoQuery .= "city";
break;
case 4:
$getSliderInfoQuery .= "profile_photo";
break;
case 5:
$getSliderInfoQuery .= "city DESC";
break;
case 6:
$getSliderInfoQuery .= "l_name DESC";
break;
}
$sliderResult = mysql_query($getSliderInfoQuery);
答案 0 :(得分:1)
您可以在没有php开关的情况下使用MySQL ORDER BY RAND()
。
$getSliderInfoQuery = "SELECT f_name, l_name, city, zipcode, pst.name as state_id, book_types, profile_photo, profile_url, prt.rating
FROM book_readers ps
left join book_states pst on pst.state_id = ps.state_id
left join book_reviews prt on prt.user_id = ps.user_id
WHERE promoted_reader = 1
ORDER BY rand()
LIMIT 2";
添加LIMIT
以获取所需的行数。
希望尽可能少地进行sql查询(并迭代行),而不是一次又一次地进行查询。
答案 1 :(得分:0)
使用mt_rand(1, 6)
,您有1/6的机会获得相同的$pickRow
。这是一段代码,可以确保您永远不会得到相同的值:
$range_values = range(1, 6);
shuffle($range_values);
$pickRow = array_pop($range_values);
// some code using $pickRow
$pickRow = array_pop($range_values);
// some code using $pickRow
添加一个数组大小的检查,这样你就不会从一个空数组中弹出,你就可以了。
干杯。