2015-06-30 103 views
3

我想從一個mysql表中動態顯示一些圖像。如何修改此循環的php?

這是我用PHP和它爲我工作的。

// Fetch all the records: 
while ($stmt->fetch()) { 

    $html = " <div class='row-fluid custom'>\n"; 
    $html .= "  <div class='span6'>\n"; 
    $html .= "  <img src='images/{$image}'>\n"; 
    $html .= "  </div>\n";                
    $html .= " </div>\n"; 

    //Add images to array 
    $images[] = $html;    
} 

這是從上面PHP標記:

<div class='row-fluid custom'> 
    <div class='span6'> 
     <img src='images/cond-1.png'> 
    </div>                 
</div> 
<div class='row-fluid custom'> 
    <div class='span6'> 
     <img src='images/cond-2.png'> 
    </div>                 
</div> 
<div class='row-fluid custom'> 
    <div class='span6'> 
     <img src='images/cond-3.png'> 
    </div>                 
</div> 
<div class='row-fluid custom'> 
    <div class='span6'> 
     <img src='images/cond-4.png'> 
    </div>                 
</div> 

但我的問題是,當我準備修改上述標記下方喜歡。

<div class="row-fluid custom"> 
    <div class="span6"> 
     <img src="images/cond-1.png"> 
    </div>         
    <div class="span6"> 
     <img src="images/cond-2.png"> 
    </div>         
</div>        
<div class="row-fluid custom"> 
    <div class="span6"> 
     <img src="images/cond-3.png"> 
    </div>         
    <div class="span6"> 
     <img src="images/cond-4.png"> 
    </div>         
</div> 

其實我顯示我的圖片時,需要將組內row-fluid DIV的兩個圖像。

任何人都可以告訴我如何使用php創建標記嗎?

希望有人可以幫助我。

謝謝。

回答

1

您需要使用modulus function在本example

$images = array('foo.jpg', 'bar.jpg','baz.jpg','glorp.jpg'); 

$html = ''; 

for($i = 0; $i < count($images); $i++){ 
    if($i % 2 == 0) { 
     $html .= " <div class='row-fluid custom'>\n"; 
     $html .= "  <div class='span6'>\n"; 
     $html .= "  <img src='images/{$images[$i]}'>\n"; 
     $html .= "  </div>\n"; 
    } else { 
     $html .= "  <div class='span6'>\n"; 
     $html .= "  <img src='images/{$images[$i]}'>\n"; 
     $html .= "  </div>\n"; 
     $html .= " </div>\n"; 
    } 
} 
echo $html; 

使用模量對2將允許你來決定需要被附加到$html變量,它的輸出。結果爲0表示數字(行)可以被2整除,允許您輸出div的開頭。任何其他結果都允許您輸出div的結尾。

+0

'for'循環或'while'循環我需要使用嗎? – user3733831

+0

你應該使用'for'循環。你可以將'fetchAll()'放入數組中,然後遍歷數組。 –

3

還在用while循環

$i = 0; 
while ($stmt->fetch()) { 
    $html = ""; 
    if($i % 2 == 0) $html = " <div class='row-fluid custom'>\n"; 
    $html .= "  <div class='span6'>\n"; 
    $html .= "  <img src='images/{$image}'>\n"; 
    $html .= "  </div>\n";                
    if($i++ % 2 == 1) $html .= " </div>\n"; 

    //Add images to array 
    $images[] = $html;    
} 
1

只需添加一個條件,以打開/關閉div

$open_div=true; 
while ($stmt->fetch()) { 
    if($open_div) 
     $html = " <div class='row-fluid custom'>\n"; 
    $html .= "  <div class='span6'>\n"; 
    $html .= "  <img src='images/{$image}'>\n"; 
    $html .= "  </div>\n"; 
    if($open_div = !$open_div)                
     $html .= " </div>\n"; 
    //Add images to array 
    $images[] = $html;    
} 

作爲一個側面說明,你的代碼引入了很多white-spaces,加起來的總頁面大小和增加頁面的下載時間。