普通网友 2018-08-05 13:12
浏览 60
已采纳

foreach Loop中的PHP表格对齐不正确

I want to display Array data in a table with 3 columns in a row using foreach loop with a condition.

Coding

$value[]='a';
$value[]='b';
$value[]='c';
$value[]='d';
$value[]='e';

echo '<table width=30% border=1>';  
    echo '<tr>';
        $counter=1; 

        foreach($value as $key){
            if($counter>=3){ // if there is more than 3 elements, go to next Row

                    if($counter%3==0){ // when the Array hit 3th,6th,9th,12th.... element
                        echo '</tr><tr><td>';               
                        echo $key;  
                        echo '</td>';                   
                    }else{
                        echo '<td>';
                        echo $key;              
                        echo '</td>';                       
                    }
            }else{
                echo '<td>';                
                echo $key;      
                echo '</td>';                   
            }           
            $counter++;
        }
    echo '</tr>';
echo '</table>';

I double check the coding and didn't manage to find the error.... my output is the bottom of the image. However, the correct one should be top of the image. Please take a look at the photo

enter image description here

Anyone know what's wrong with my coding?

  • 写回答

3条回答 默认 最新

  • doutui2883 2018-08-05 13:23
    关注

    Change modulas condition with

    if($counter % 3 == 1)
    

    and you will get what you desire

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?