问题
//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>
}
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>
I cant find out how to either get the index of the associative array, or how to break a foreach loop once %3 == 0.
Any suggestions would be awesome!
-Ved
回答1:
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 -->
回答2:
Are you looking for this? php.net/array_chunk
And, you have some syntax error there
foreach($info as $key => $val){
this should be
foreach($info as $key => $val){ ?>
closing php to start the HTML tag
回答3:
You would want to do something like this in that case. Make sure to get the variables right.
$i = 1;
foreach($info as $key => $val){
if ($i % 3 == 0) {
?>
<div name='container'>
<?php
}
?>
<div class="holder">
<div class="name">
<?php echo $key; ?>
</div>
<div class="colour">
<?php echo $val; ?>
</div>
</div>
if ($i % 3 == 2) {
?>
</div>
<?php
}
<?php
$i++;
}
回答4:
You can increment $i
it inside the foreach loop, e.g:
$i = 0;
foreach ($info as $key => $val) {
if ($i % 3 == 0) {
...
} else {
...
}
$i++;
}
来源:https://stackoverflow.com/questions/13270870/wrapping-a-div-around-every-third-item-in-a-foreach-loop-php