![](/img/trans.png)
[英]How do you make sure two rows selected at random are different from one another?
[英]How can I make sure that two rows selected at random are different from one another?
我有一張桌子上的photos
有很多照片,我需要隨機選擇兩個:
在getnew.php
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$result2 = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 1");
$row = $result->fetch_assoc();
$img1link = $row['link'];
// more stuff from $row
$row2 = $result2->fetch_assoc();
$img2link = $row2['link'];
// more stuff from $row2
但是,我需要防止它兩次選擇同一張照片(所選照片必須不同),即$img1link
不應= $img2link
。 那么我需要使用檢索數據$.getJSON
在另一個文件中,使用在結束數組getnew.php
。
getnew.php結尾的數組:
echo json_encode(array('img1'=>$img1link,'img2'=>$img2link, ...(etc)... ));
如何在變量存儲到數組中時確保所選的照片不同? 我試圖創建一個if / else語句,但並沒有真正理解我在做什么。
您只能執行一次,而只能執行兩次,所以您永遠不會選擇同一行:
$result = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 2");
$row = $result->fetch_assoc();
$row2 = $result->fetch_assoc();
// invoke `->fetch` twice to get the first and second row
$img1link = $row['link'];
$img2link = $row2['link'];
旁注:請注意該ORDER BY rand()
子句,因為在大型數據集上它會變慢。 您可以在@Bill Karwin的出色答案中使用替代方法
運行一個查詢-
$result1 = mysqli_query($conn,"SELECT * FROM photos ORDER BY rand() LIMIT 2");
while($row = $result->fetch_assoc()) {
$imglink[] = $row['link'];
}
您將在$imglink[]
數組中獲得鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.