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

通过一个数组循环,每个第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>';
    
    点赞 评论
  • dsflxcfuw27742248 2019-04-16 22:59

    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>';
    
    点赞 评论

相关推荐 更多相似问题