Reputation: 2373
I have an array and now I'm putting this array into for loop
to show each item in this array, but I want set item limit (4 item each column), here is my code.
<?php
$area = $custom_area_settings; //is an array with 5 element
for($i=0;$i<=count($area->custom_area_list) - 1; $i++):
if($area->custom_area_list[$i]->top_show):
echo '<div class="sub-column column'.$i.'">';
echo '<p class="line"> ' . $area->custom_area_list[$i]->header . '</p>';
echo '</div>';
endif;
endfor;
?>
On this code, div column$i
had created each time loop ran but I just want this div create when loop run 4 times, after 4 times this div will create again, after 8 times this div will create again and continue...
Here is the result I want.
Column 1 Column 2
--------------- ---------------
item 1 item 5
item 2 item 6
item 3 item 7
item 4 item 8
Here is the result I'm getting now
Column 1
---------------------
item 1
Column 2
---------------------
item 2
.....
Please help.
Upvotes: 3
Views: 167
Reputation: 5094
Updated:
$html = $i%4 === 0 ? '<div class="sub-column column'
. $i . '">'
. '{1}' . '</div>' : '{1}';
echo strtr($html,array('{1}' => '<p class="line"> '
. $area->custom_area_list[$i]->header
. '</p>'
));
% divides $i by 4 and returns the remainder which must be equal to 0 in this case
Upvotes: 5
Reputation: 284
I would recommend you use the array_chunk
command
Example
$chunkedArray = array_chunk(['One', 'Two', 'Three', 'Four', 'Five'], 4);
echo '<div class="row">';
array_walk( $chunkedArray, function($array)
{
echo '<div class="col-md-4">'
foreach( $array as $key => $value )
{
echo "<p class='line'>$value</p>";
}
echo '</div>';
});
echo '</div>';
This example was created using twitter bootstrap css classes. I'm sure it could be optimized, just showcasing the array_chunk approach.
Upvotes: 1
Reputation: 171
<?php
$area = $custom_area_settings; //is an array with 5 element
$i=0;
echo '<div class="sub-column column'.$i.'">';
for($i=0;$i<=count($area->custom_area_list) - 1; $i++):
if($area->custom_area_list[$i]->top_show):
if($i%4 === 0):
echo '</div>';
echo '<div class="sub-column column'.$i.'">';
endif;
echo '<p class="line"> ' . $area->custom_area_list[$i]->header . '</p>';
endif;
endfor;
echo '</div>';
?>
Upvotes: 1