I’ve got an array of 28 titles and i need to run through the array and display 2 items(titles) at a time into the following html:
<ul>
//start loop here for all items in array
<li>
//display two titles in seperate divs
<div class="item1">
<h1>title[x]</h1>
</div>
<div class="item2">
<h1>title[x]</h1>
</div>
</li>
//repeat...
</ul>
So basically it outputs like the following:
<ul>
<li>
<div>
<h1>Title 1</h1>
</div>
<div>
<h1>Title 2</h1>
</div>
</li>
<li>
<div>
<h1>Title 3</h1>
</div>
<div>
<h1>Title 4</h1>
</div>
</li>
<li>
<div>
<h1>Title 5</h1>
</div>
<div>
<h1>Title 6</h1>
</div>
</li>
//etc..
</ul>
This is what I’ve tried so far, obviously it just duplicated both titles.
<div id="work-list">
<ul class="work-list-cat group">
<?php if (!empty($this->intro_items)) {
foreach($this->intro_items as $id => $item) {
$itemarray[] = $item;
}
$count = count($itemarray);
$item = 1;
for($y = 0; $y < $count; $y++) {
?>
<li style="width:33.333333333333333333333333333333%; height:100%; float:left;">
<?php
for($x=0; $x<$item; $x++){ ?>
<div style="width:100%; height:50%; float:left; background-color:#333;">
<?php echo $itemarray[$y]->title; ?>
</div>
<div style="width:100%; height:50%; float:left; background-color:#444;">
<?php echo $itemarray[$y]->title; ?>
</div>
<?php } ?>
</li>
<?php } ?>
<?php } ?>
</ul>
</div> <?php //End of #work-list ?>
Ah, and you’re stumped because it’s not working with a
foreachloop, I reckon? It’s times like these that the good ol’ for-loop comes in handy, incrementing the index with 2 at a time. Something like this might be what you’re looking for:Note: it won’t work for arrays with an odd number of elements, but seeing as you have 28, that shouldn’t be an issue. EDIT: When there’s an odd number of elements, it will simply print an empty div and h1-tag at the end.
PS: As you didn’t ask a really specific question, I could’ve misinterpreted your problem entirely.. Try to be a bit more precise in formulating the issue if this doesn’t help you out.