duannaxin9975 2019-04-16 22:46
浏览 173
已采纳

通过一个数组循环,每个第6个元素换行作为一个表?

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条回答 默认 最新

  • dtip91401 2019-04-16 23:31
    关注

    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>';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?