简体   繁体   English

PHP表对齐在foreach循环中不正确

[英]PHP table alignment is not correct inside foreach Loop

I want to display Array data in a table with 3 columns in a row using foreach loop with a condition. 我想使用带有条件的foreach循环在连续3列的表中显示Array数据。

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 请看照片

在此处输入图片说明

Anyone know what's wrong with my coding? 有人知道我的编码有什么问题吗?

Change modulas condition with 更改模态条件

if($counter % 3 == 1)

and you will get what you desire 你会得到你想要的

您具有“ if counter> = 3”,因此您在第三个元素上而不是在第三个元素之后达到该条件。

将计数器的初始化更改为$counter=0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM