Looping through an array with line breaks every 6th element as a table?

时间:2019-04-16 22:46:20

标签: php sorting

I am trying to print an array so every 6th element is on a new line. I'm trying to do this in a table. I would prefer if it could be answered in PHP, but Javascripts Ok.

$array_control = array(
"1","5","6","2","1",
"2","1","6","4","3",
"3","2","5","6","6",
"4","3","1","5","4",
"6","4","2","3","6"
);
$arrayLength = count($array_control);

    $i = 0;

    while ($i < $arrayLength)
    {
        if ($i==0) {
            echo "<tr>";
        }
       if (is_int($i/5)) {
         echo '<td style="width:16%;">'.$array_control[$i].'</td>';
         echo "</tr>";
            echo "<tr>";

        }else{
             echo '<td style="width:16%;">'.$array_control[$i-1].'</td>';

        }

        $i++;


    }

Any help would be great!

2 个答案:

答案 0 :(得分:0)

A for loop seems better, and maybe the mod operator is more clear.

echo '<tr>';
for ($i < = 0; i < $arrayLength; ++ $i) {
    echo '<td style="width:16%;">'.$array_control[$i].'</td>';
    if ($i % 6 == 5) {
        echo '</tr>';
        echo '<tr>';
    }
}
echo '</tr>';

This isn't quite ideal, because you'll get an empty '' at the end, but the browser should hide that. A little more logic can be added if you need to eliminate that too.

Further, with the array structure you're showing, you could eliminate the $arrayLength variable entirely, and instead use:

foreach ($array_control as $i => $val) {
    echo '<td style="width:16%;">'.$val.'</td>';

答案 1 :(得分:0)

The %-operator (modulus) solves this for you:

echo '<table><tr>';
for($i = 1; $i <= count($array_control); $i++ ){
    echo '<td style="width:16%;">';
    if( ($i % 6) == 0){
        echo $array_control[$i-1] . '</td></tr><tr>';  
    } else{
        echo $array_control[$i-1] . '</td>';
    }
}
echo '</tr></table>';

or if you feel sassy:

echo '<table><tr>';
for($i = 1; $i <= count($array_control); $i++ ){
    echo '<td style="width:16%;">' . $array_control[$i-1], ( ($i % 6) == 0 ) ? '</td></tr><tr>' : '</td>';
}
echo '</tr></table>';