2013-07-17 58 views
2

我試圖用CSS來設計一些DIV。我想要做的是使用PHP在MySql循環內改變DIV標籤類。用PHP更改DIV類

<?php 
$result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20"); 
while($row = mysqli_fetch_array($result)) 
    { 
?> 
<div class=」 box id1」><?php echo $row[‘post’];?></div> 
<?php } ?> 

所以我想改變類盒ID1以該順序

box id1 
box id1 
box id2 
box id2 
box id2 
box id2 
box id1 
box id1 
box id2 
box id2 
box id2 
box id2 
So on. (2 div tags with the class box id1 then 4 with box id2 looping) 

我嘗試使用蘭特(1,2);但是這使得數字隨機不是爲了我想要的順序。任何幫助都感激不盡。提前致謝。

回答

3
<?php 
$result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20"); 

$i=1; 
$class_str = ""; 
while($row = mysqli_fetch_array($result)) 
{ 
    switch($i%6){//deciding for six place 
     //first two id1 
     case 1: 
     case 2: 
      $class_str="id1"; 
     break; 
     //four other id2 
     case 3: 
     case 4: 
     case 5: 
     case 0: 
      $class_str="id2"; 
     break; 
    } 
$i++; 

?> 
    <div class="box <?php echo $class_str; ?>"><?php echo $row['post'];?></div> 

<?php } ?> 
+0

謝謝你的工作很棒:) – maxlk

0

嘗試使用if循環和$ count變量來確定您迭代了多少次SQL查詢結果。

<?php 
$result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20"); 
$count = 1; 
while($row = mysqli_fetch_array($result)) 
{ 
    // If count is <= 2, set boxId = 1 
    if($count <= 2) { 
     $boxId = 1; 
     $count += 1; 
    // If count is <= 6, set boxId = 2 
    } elseif($count <= 6) { 
     $boxId = 2; 
     $count += 1; 
    // Once we have two id1 and four id2, reset count to 1 
    } else { 
     $count = 1; 
    } 
?> 
<div class="box id<?php echo $boxId; ?>"><?php echo $row[‘post’];?></div> 
<?php } ?> 
0

利用InfiniteIterator

<?php 
$infinite = new InfiniteIterator(new ArrayIterator(array(1, 1, 2, 2, 2, 2))); 
$infinite->rewind(); 

$result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20"); 
while($row = mysqli_fetch_array($result)) { 
    $current = $infinite->current(); 
    $infinite->next(); 
?> 
<div class="box id<?php echo $current; ?>"><?php echo $row['post'];?></div> 
<?php } ?> 
0

基本數學運算符。

<?php 
$result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20"); 
$count = 0; 
while($row = mysqli_fetch_array($result)) 
    { 
?> 
    <div class=」 box id<?php echo min((($count/2 % 3)+1),2); ?>」><?php echo $row[‘post’];?></div> 
<?php 
    $count++; 
} ?> 

如果你總是確保自己的帖子會0-20,你可以跳過$計數,只需使用$行[「身份證」。