php – 每3条记录后新包含div
发布时间:2020-12-13 21:27:46 所属栏目:PHP教程 来源:网络整理
导读:我想创建一个新的包含 div 3个结果后,使用PDO结果循环. 对于我的自学项目,我必须制作一个带引导程序的产品页面,并且在每第3条记录之后我必须创建一个新行并再次显示3个col-md-4等等. 现在我把它作为我的代码: div class="row" ?php while ($row = $stmt-fet
我想创建一个新的包含< div> 3个结果后,使用PDO结果循环.
对于我的自学项目,我必须制作一个带引导程序的产品页面,并且在每第3条记录之后我必须创建一个新行并再次显示3个col-md-4等等. 现在我把它作为我的代码: <div class="row"> <?php while ($row = $stmt->fetch(PDO::FETCH_OBJ)) { ?> <div class="col-md-4"> <div class="product"> <div class="title"><?php echo $row->pname ?></div> <div class="img"><img src="../product/img/<?php echo $row->pnumber ?>/<?php echo $row->pthumbnail ?>.jpg?$pop210x210$"/> </div> <div class="vijftien"></div> <div class="deliver">Levertijd: <strong><?php echo $row->pdelivertime ?></strong></div> <div class="vijf"></div> <div class="other"></div> <div class="row"> <div class="col-md-6"> <div class="price"><?php echo $row->pprice ?></div> </div> <div class="col-md-6"> <div class="order"> <button class="log_in" id="doLogin">Meer informatie</button> </div> </div> </div> </div> </div> <?php } ?> </div> 我已经访问并研究了其他问题,但我并没有真正理解他们是如何做到的,以及如何在我的代码中实现正确的方法. 解决方法
正如塔德曼在你提问的评论中所述.最佳方法应使用
modulus operator(%)和3.
将分离条件放在每次迭代的开始处. (Demo) 像这样: $x=0; // I prefer to increment starting from zero. // This way I can use the same method inside a foreach loop on // zero-indexed arrays,leveraging the keys,and omit the `++` line. echo "<div class="row">"; foreach($rows as $row){ if($x!=0 && $x%3==0){ // if not first iteration and iteration divided by 3 has no remainder... echo "</div>n<div class='row'>"; } echo "<div>$row</div>"; ++$x; } echo "</div>"; 这将创建: <div class="row"><div>one</div><div>two</div><div>three</div></div> <div class='row'><div>four</div><div>five</div><div>six</div></div> 延迟编辑,这里有几个类似情况的其他方法,它们将提供相同的结果: foreach(array_chunk($rows,3) as $a){ echo "<div class="row"><div>",implode('</div><div>',$a),"</div></div>n"; } 要么 foreach ($rows as $i=>$v){ if($i%3==0){ if($i!=0){ echo "</div>n"; } echo "<div class="row">"; } echo "<div>$v</div>"; } echo "</div>"; 澄清什么不做…… Sinan Ulker的答案将导致不必要的结果,具体取决于结果数组的大小. 以下是公开问题的一般化示例: 使用此输入数组来表示您的pdo结果: $rows=["one","two","three","four","five","six"]; 思安在每次迭代结束时的情况: $i=1; echo "<div class="row">"; foreach($rows as $row){ echo "<div>$row</div>"; if($i%3==0)echo "</div>n<div class='row'>"; // 6%3==0 and that's not good here // 6%3==0 and will echo the close/open line after the content to create an empty,unwanted dom element $i++; } echo "</div>nn"; 会创建这个: <div class="row"><div>one</div><div>two</div><div>three</div></div> <div class='row'><div>four</div><div>five</div><div>six</div></div> <div class='row'></div> //<--- this extra element is not good (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |