我试图同时迭代2个div来回显数据库中的数据。每个div都有它自己的风格,我想继续迭代,每个div两次没有重复,而不会失去我的div风格。即使我从我的数据库中删除任何帖子,我也不想丢失div设计安排(奇数/偶数显示),任何帮助或建议?
// class getAll to get all posts from db tables
class getALL {
private $pdo;
public function __construct() {
$this->pdo = db::getInstance();
}
public function get() {
$sql = "SELECT * FROM `posts`";
$q = $this->pdo->prepare($sql);
$q->execute();
if($q->rowCount()) {
return $q->fetchAll(PDO::FETCH_OBJ);
}
return false;
}
}
这里是2个div的部分
// the 2 divs with iteration
<? if(is_array($getArticles) || is_object($getArticles)): ?>
<? foreach($getArticles as $getArticle): ?>
<? if($getArticle->id % 2 == 0) { ?> //odd/even logic
<!-- One -->
<article id="one" class="post style1">
<div class="image">
<img src="<?='images/'.$getArticle->image_name?>" alt="" data-position="75% center" />
</div>
<div class="content">
<div class="inner">
<header>
<h2><a href="post.html"><?=$getArticle->title?></a></h2>
<p class="info"><?=$getArticle->post_time?> by <a href="#"><?=$getArticle->username?></a></p>
</header>
<p><?=$getArticle->post?></p>
<ul class="actions">
<li><a href="post.php" class="button alt">Read More</a></li>
</ul>
</div>
</div>
</article>
<? }else{ ?>
<!-- two -->
<article id="four" class="post invert style2 alt">
<div class="image">
<img src="<?='images/'.$getArticle->image_name?>" alt="" data-position="60% center" />
</div>
<div class="content">
<div class="inner">
<header>
<h2><a href="post.php"><?=$getArticle->title?></a></h2>
<p class="info"><?=$getArticle->post_time?> by <a href="#"><?=$getArticle->username?></a></p>
</header>
<p><?=$getArticle->post?></p>
<ul class="actions">
<li><a href="post.php" class="button alt">Read More</a></li>
</ul>
</div>
</div>
</article>
<? } ?>
<? endforeach; ?>
<? endif; ?>
答案 0 :(得分:1)
使用简单的$getArticle->id
变量将两个div组合在一起并实现奇偶逻辑,而不是$counter
。这样,当你删除帖子时,它不会破坏div安排。这是解决方案:
<?php $counter = 0; ?>
<?php if(is_array($getArticles) || is_object($getArticles)): ?>
<?php foreach($getArticles as $getArticle): ?>
<article id=<?php if($counter % 2 == 0){ echo "one"; }else{ echo "four"; } ?> class="post<?php if($counter % 2 == 0){ echo " style1"; }else{ echo " invert style2 alt"; } ?>">
<div class="image">
<img src="<?='images/'.$getArticle->image_name?>" alt="" data-position="<?php if($counter % 2 == 0){ echo "75%"; }else{ echo "60%"; } ?> center" />
</div>
<div class="content">
<div class="inner">
<header>
<h2><a href="post.php"><?=$getArticle->title?></a></h2>
<p class="info"><?=$getArticle->post_time?> by <a href="#"><?=$getArticle->username?></a></p>
</header>
<p><?=$getArticle->post?></p>
<ul class="actions">
<li><a href="post.php" class="button alt">Read More</a></li>
</ul>
</div>
</div>
</article>
<?php ++$counter; ?>
<?php endforeach; ?>
<?php endif; ?>