环绕周围的每个第三项的div在foreach循环PHP [英] Wrapping a div around every third item in a foreach loop PHP

查看:94
本文介绍了环绕周围的每个第三项的div在foreach循环PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//set the array
$info = array(
'andy' => 'blue',
'andrew' => 'black',
'mark' => 'green',
'jane' => 'orange',
'simon' => 'red',
'joan' => 'pink',
'sue' => 'yellow',
'alan' => 'black') 


$i = 1;

foreach($info as $key => $val){

    <div class="holder">
        <div class="name">
            <?php echo $Name ?> 
        </div>
        <div class="colour">
            <?php echo $colour ?> 
        </div>
    </div>
} 

这dispalys每个持有级......但我所想要做的是包装容器围绕持有级,并在每个集装箱有3个持有人。
例如:

This dispalys each "holder" class... but what I am wanting to do is wrap a container around the "holder" class and have 3 "holder" in each "container". eg:

<div class="container">
    <div class="holder">
            <div class="name">
                <?php echo $Name ?> 
            </div>
            <div class="colour">
                <?php echo $colour ?> 
            </div>
        </div>
    <div class="holder">
            <div class="name">
                <?php echo $Name ?> 
            </div>
            <div class="colour">
                <?php echo $colour ?> 
            </div>
        </div>
    <div class="holder">
            <div class="name">
                <?php echo $Name ?> 
            </div>
            <div class="colour">
                <?php echo $colour ?> 
            </div>
        </div>
</div>

我不能找出如何要么得到关联数组的索引,或者如何打破foreach循环一旦%3 == 0,

I cant find out how to either get the index of the associative array, or how to break a foreach loop once %3 == 0.

任何建议将是真棒!

-Ved

推荐答案

您需要有一个独立的计数器变量:

You need to have a separate counter variable:

$i = 0;
foreach($info as $key => $val){
  if($i%3 == 0) {
    echo $i > 0 ? "</div>" : ""; // close div if it's not the first
    echo "<div class='container'>";
  }
  ?>
    <div class="holder">
        <div class="name">
            <?php echo $Name ?> 
        </div>
        <div class="colour">
            <?php echo $colour ?> 
        </div>
    </div>
<?php
$i++;
}
?>
</div> <!-- close last container div -->

这篇关于环绕周围的每个第三项的div在foreach循环PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆