簡體   English   中英

使用for循環組合PHP優化MYSQL查詢,同時循環輸出

[英]Optimize a MYSQL query while loop output with a for loop combination PHP

我試圖從樣式上稍微不同地從mysql查詢輸出每一行,但是我想避免使用偏移量和多個查詢。

當前代碼:

$sql = "SELECT * FROM news ORDER BY id DESC LIMIT 1";
$query = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($query)){
$title = $row["title"];
// output first news item with a style
echo '<div class="style-1">'.$title.'</div>';
}

$sql = "SELECT * FROM news ORDER BY id DESC LIMIT 1 OFFSET 1";
$query = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($query)){
$title = $row["title"];
// output second news item with different style
echo '<div class="style-2">'.$title.'</div>';
}

因此,我想避免使用2個(或多個)簡單查詢,因為我想為while每一行使用不同的CSS類,如下所示:

$sql = "SELECT * FROM news ORDER BY id DESC LIMIT 10";
$query = mysqli_query($connection, $sql);
while($row = mysqli_fetch_array($query)){
$title = $row["title"];
} // end while
$i = 1;
for($i; $i<2; $i++){ // output first row item with first style
echo '<div class="style-1">'.$title.'</div>';
} // end for loop 1
for($i; $i<3; $i++){ // output first row item with second style
echo '<div class="style-2">'.$title.'</div>';
} // end for loop 2
for($i; $i<4; $i++){ // output third row item with third style
echo '<div class="style-3">'.$title.'</div>';
} // end for loop 3
    ...

所需輸出:

<div class="style-1">News Headline Title 1</div>
<div class="style-2">News Headline Title 2</div>
<div class="style-3">News Headline Title 3</div>
...

我假設您想要3種不同的樣式,這就是我要完成的方式:

$sql = "SELECT * FROM news ORDER BY id DESC LIMIT 10";
$query = mysqli_query($connection, $sql);

$i = 1;

while($row = mysqli_fetch_array($query)){
    $title = $row["title"];
    if($i<2){
        $styleNumber = 1;
    }
    else if($i<3){
        $styleNumber = 2;
    }
    else if($i<4){
        $styleNumber = 3;
    }
    echo '<div class="style-'.$styleNumber.'">'.$title.'</div>';
    $i++;
} 
// end while

輸出
標題1(樣式1)
標題2(樣式2)
標題3(樣式3)
標題4(樣式3)

這不是答案。 由於@JonTan答案被選為正確答案,因此僅是對它的評論/改進。

我的猜測是,OP需要為每3條記錄循環樣式,而不是僅為3個首先返回的樣式設置樣式。

這意味着我們可以將條件從if($i<3){if($i<2){更改為以下內容:

$i = 1;

while($row = mysqli_fetch_array($query)){
    $title = $row["title"];
    if($i % 3 == 0){
        $styleNumber = 3;
    } else if($i % 2 == 0){
        $styleNumber = 2;
    } else {
        $styleNumber = 1;
    }
    echo '<div class="style-'.$styleNumber.'">'.$title.'</div>';
    $i++;
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM