2

我正在尝试使用 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”&gt;<?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

4 回答 4

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 } ?>
于 2013-07-17T17:43:47.543 回答
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 } ?>
于 2013-07-17T17:27:06.143 回答
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); ?>”&gt;<?php echo $row[‘post’];?></div>
<?php 
    $count++;
} ?>

如果您始终确定您的帖子将是 0-20,您可以跳过 $count 并使用 $row["id"]。

于 2013-07-17T17:42:20.083 回答
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 } ?>
于 2013-07-17T17:33:24.887 回答