我有一个表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 的替代方案 answer
关于php - 如何确保随机选择的两行彼此不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30121717/