用PHP更改DIV类

时间:2013-07-17 17:16:40

标签: php

我正在尝试使用CSS设置一些DIV的样式。我想要做的是使用PHP更改MySql循环中的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)

我尝试使用rand(1,2);但这使得数字随机而不是我想要的顺序。任何帮助都感激不尽。提前谢谢。

4 个答案:

答案 0 :(得分: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 } ?>

答案 1 :(得分: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 } ?>

答案 2 :(得分: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 } ?>

答案 3 :(得分: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,你可以跳过$ count并使用$ row [“id”]。