PHP数组在列表中获取每个5

时间:2016-09-28 14:05:42

标签: php arrays list

$ cars = array(&#34; A&#34;,&#34; B&#34;,&#34; C&#34;,&#34; D&#34;,&#34; E&# 34;,&#34; F&#34;,&#34; G&#34;,&#34; H&#34;,&#34; I&#34;,&#34; J&#34;); < / p>

我需要为此结构中的每5行获得2个col-lg-2:

$车

怎么办?

我做的前5行:

<div class='col-lg-2'><ul>
<?php $i=0;
foreach($cars as $car){
  echo "<li>$car</li>";
  $i++;
  if($i==5) break;
} ?>
</ul></div>

我怎样才能回应下一个5?

3 个答案:

答案 0 :(得分:2)

使用array_chunk()

通过使用array_chunk(),您可以生成一个多维数组,每个数组包含5个元素。

$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>";
} 

https://eval.in/652005

使用模数

通过使用模数运算符(%),您可以检查您的计数器($i)是否可被5整除,如果是,则结束当前<div>并开始一个新的<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>';

https://eval.in/651965

答案 1 :(得分:0)

根据建议使用模数除法运算符,这是一个可能的解决方案;

$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;

N.B。将div作为ULexplained here

的孩子的General无效的html

答案 2 :(得分:-1)

<?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>