$cars = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J");
I need to get 2 col-lg-2 for each 5 rows inside this structure:
$carhow can it done ?
for the first 5 rows i made this:
<div class='col-lg-2'><ul> <?php $i=0; foreach($cars as $car){ echo "<li>$car</li>"; $i++; if($i==5) break; } ?> </ul></div>
how can I echo the next 5 ?
array_chunk()
By using array_chunk()
you can generate a multi-dimensional array, with 5 elements in each.
$cars = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J");
$carsGrouped = array_chunk($cars, 5);
foreach($carsGrouped as $carGroup){
echo "<div class='col-lg-2'><ul>";
foreach($carGroup as $car) {
echo "<li>{$car}</li>";
}
echo "</ul></div>";
}
By using the modulus operator ( %
) you can check if your counter ( $i
) is divisible by 5
, and if it is, then end the current <div>
and start a new <div class='col-lg-2'>
.
$cars = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J");
echo '<div class=\'col-lg-2\'>
<ul>';
$i = 0;
foreach($cars as $car){
++$i;
echo '<li>'. $car .'</li>';
if($i>1 AND ($i%5)===0 AND $i<count($cars)) { //We've printed 5 $car, we need to do another "group".
echo '</ul>
</div>
<div class=\'col-lg-2\'>
<ul>';
}
}
echo '</ul>
</div>';
Using the modulus division operator as suggested, here is a possible solution;
$cars = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "s", "ee");
$iCount = 0;
$sOutput = '';
foreach($cars as $sCarName){
if ($iCount % 5 == 0)
$sOutput .= ($iCount > 1 ? "</ul>\n</div>\n" : '')."<div class='col-lg-2'>\n<ul>\n";
$sOutput .= "<li>".$sCarName."</li>\n";
$iCount ++;
}
if( $iCount > 1 ){
$sOutput .= "</ul>\n</div>";
}
echo $sOutput;
NB its not valid html to have a div
as a child of an UL
, explained here
<?php
$cars = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J");
?>
<div class='col-lg-2'><ul>
<?php
$i=0;
foreach($cars as $car_name){
echo "<li>$car_name</li>";
$i++;
if($i==5):
echo "</ul></div><div class='col-lg-2'><ul>";
$i = 0;
endif;
}
?>
</ul></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.