我该如何解决这个php mysql循环?

时间:2012-08-23 14:49:46

标签: php mysql

<?

$sql = dbquery("SELECT `id`, `title`, `description` FROM `content` LIMIT 0,12 ");
while ($row = mysql_fetch_array($sql)) {
    $id          = $row["id"];
    $title       = $row["title"];
    $description = $row["description"];
    $content     = '
    <div class="description-box">
    <p>page id: ' . $id . '</p>
    <p>' . $title . '</p>
    <p>' . $description . '</p>
    </div>';
}

echo $content;
?>

// notice:div class =“description-box”

//如何在每3个输出div后用:div class =“description-box nopadding”替换它?

html生成代码示例:

<div class="description-box nopadding">
// content
</div>
<div class="description-box">
// content
</div>
<div class="description-box">
// content
</div>
<div class="description-box">
// content
</div>

//再次使用nopadding

的div

2 个答案:

答案 0 :(得分:5)

<div class="description-box'.(($c++%3==0)?' nopadding':'').'">

记得初始化$c

这很简单:

如果除以$c除以3的余数为0,则添加' nopadding'字符串,否则添加'' stirng

0 % 3 == 0 // add
1 % 3 == 1
2 % 3 == 2
3 % 3 == 0 // add
4 % 3 == 1
...

语法:

echo true ? "it's true" : "it's false"; // it's true
echo (5 % 3); // 2, remainder of 5/3 division
$c = 0;
echo $c++; // 0
echo $c;   // 1

答案 1 :(得分:0)

<?
$sql = dbquery("SELECT `id`, `title`, `description` FROM `content` LIMIT 0,12 ");
$counter = 0; 
while($row = mysql_fetch_array($sql)){  
$id = $row["id"];   
$title = $row["title"];
$description = $row["description"];
if($counter%3 == 0)
{
 $div = '<div class="description-box nopadding">'
}
else
{
 $div = '<div class="description-box">';
}
 content = $div.'
 <p>page id: '.$id.'</p>
 <p>'.$title.'</p>
 <p>'.$description.'</p>
 </div>';
 $counter++;
}

echo $content;  ?>