Php 在带有循环的默认表中显示数据数组

Php 在带有循环的默认表中显示数据数组,php,Php,我有1个数组数据也可能更多,并且希望将其显示在表中,我尝试将默认表设置为5列,但当我尝试相同的结果时,5列显示了其所有数据。应该有3列2列是空的,我的脚本缺少什么 这个myscript <?php $no = 1; for($x=1; $x<=5; $x++) { foreach ($mydata as $row) { echo '<tr>'; echo '<td>'.$no.'</td>';

我有1个数组数据也可能更多,并且希望将其显示在表中,我尝试将默认表设置为5列,但当我尝试相同的结果时,5列显示了其所有数据。应该有3列2列是空的,我的脚本缺少什么

这个myscript

<?php
$no = 1;
for($x=1; $x<=5; $x++) {
    foreach ($mydata as $row) {
        echo '<tr>';
        echo '<td>'.$no.'</td>';
        echo '<td>'.$row->id.'</td>';
        echo '<td>'.$row->name.'</td>';
        echo '<td>'.$row->class.'</td>';
        echo '</tr>';
        $no++;
    }
}
?>
我预料

NO  | ID  | NAME | ClASS |
____|____ |______|_______|
 1  | 001 | Paul |   x   |
 2  |     |      |       |
 3  |     |      |       |
 4  |     |      |       |
 5  |     |      |       |
试试这个:

<?php
$no = 1;
for ($x=1; $x <= 5; $x++) {
    if (isset($mydata[$x-1])) {
        $row = $mydata[$x-1];
        echo '<tr>';
        echo '<td>'.$no.'</td>';
        echo '<td>'.$row->id.'</td>';
        echo '<td>'.$row->name.'</td>';
        echo '<td>'.$row->class.'</td>';
        echo '</tr>';
    } else {
        echo '<tr>';
        echo '<td>'.$no.'</td>';
        echo '<td></td>';
        echo '<td></td>';
        echo '<td></td>';
        echo '</tr>';
    }
    $no++;
}
?>


您需要检查数据是否基于
$x
var设置,然后呈现空行或填充。

您不需要嵌套循环。只需从
1
5
的单个循环,每次迭代都会显示数组的相应元素,如果没有这样的元素,则显示空单元格

for ($x = 1; $x <= 5; $x++) {
    echo "<tr>";
    echo "<td>" . $x . "<td>";
    if (isset($mydata[$x-1])) {
        $row = $mydata[$x-1];
        echo '<td>'.$row->id.'</td>';
        echo '<td>'.$row->name.'</td>';
        echo '<td>'.$row->class.'</td>';
    } else { // show empty fields
        echo "<td></td><td></td><td></td>"; 
    }
    echo "</tr>";
}
用于($x=1;$x id.”;
回显“.$row->name.”;
回显“.$row->class.”;
}else{//显示空字段
回声“;
}
回声“;
}

也不需要单独的变量
$x
$no

echo”“;print\r($mydata);echo“”;
并与我们共享此数组问题中的行和列似乎混淆了。非常感谢@divix您的回答非常有帮助,符合我的预期。感谢您帮助我解决问题,答案需要运行,但divix的答案解决了我的问题。
for ($x = 1; $x <= 5; $x++) {
    echo "<tr>";
    echo "<td>" . $x . "<td>";
    if (isset($mydata[$x-1])) {
        $row = $mydata[$x-1];
        echo '<td>'.$row->id.'</td>';
        echo '<td>'.$row->name.'</td>';
        echo '<td>'.$row->class.'</td>';
    } else { // show empty fields
        echo "<td></td><td></td><td></td>"; 
    }
    echo "</tr>";
}