//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> }
这显示了每个“持有者”类…但我想要做的是在“持有者”类周围包装一个容器,并在每个“容器”中有3个“持有者”.
例如:
<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>
我不知道如何获得关联数组的索引,或者如何在%3 == 0时打破foreach循环.
任何建议都很棒!
-Ved
解决方法
你需要一个单独的计数器变量:
$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 -->