注意:我是 PHP 初学者,这就是为什么下面的代码可能不好的原因。
你好。我目前正在使用此代码来选择 9 个唯一的随机行,它工作正常。
$quCountRows = $database->query("SELECT * FROM approved")->rowCount();
$arrRandomPictures = array();
while (count($arrRandomPictures) < 9) {
$randNumber = mt_rand(1, $quCountRows);
if (!in_array($randNumber, $arrRandomPictures)) {
$arrRandomPictures[] = $randNumber;
}
}
$quRandomPicture1 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[0]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture2 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[1]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture3 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[2]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture4 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[3]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture5 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[4]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture6 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[5]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture7 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[6]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture8 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[7]."'")->fetch(PDO::FETCH_ASSOC);
$quRandomPicture9 = $database->query("SELECT picName,picType FROM approved WHERE id='".$arrRandomPictures[8]."'")->fetch(PDO::FETCH_ASSOC);
虽然它可能有效,但我很确定用更少的查询可以获得相同的结果。希望这会导致页面加载更快。
有什么建议么?
这是更好的代码。感谢琥珀!
$quCountRows = $database->query("SELECT * FROM approved")->rowCount();
$arrRandomPictures = array();
while (count($arrRandomPictures) < 9) {
$randNumber = mt_rand(1, $quCountRows);
if (!in_array($randNumber, $arrRandomPictures)) {
$arrRandomPictures[] = $randNumber;
}
}
$quRandomPicture = $database->query("SELECT picName,picType FROM approved WHERE id IN (".implode(', ', $arrRandomPictures).")")->fetchAll(PDO::FETCH_ASSOC);