PHP 使用 POST 信息创建表,循环遍历填充的变量

标签 php html loops post html-table

我有以下帖子变量:

$line_1_09
$line_1_12
$line_1_15
$line_1_18
$line_1_21
$line_2_09
$line_2_12
$line_2_15
$line_2_18
$line_2_21
$line_3_09
$line_3_12
$line_3_15
$line_3_18
$line_3_21

我从我以前的表格中得知,在 15 个输入(帖子)中,有 12 个已填充。 12 存储在变量 $populatedrows 中。

然后我想在我的新页面上创建一个表

<table>
<?php for ($i=1; $i<=$populatedrows; $i++)
  {
?>
    <tr>
       <td>
         <input type="text" value="//first post with information//">
       </td>
    </tr>
<?php } ?>
</table>

因此在此示例中,如果 $line_1_09$line_1_12 为空,则第一个表格行输入必须是 $line_1_15

因此它将继续“循环”通过下一个可用/填充的后变量,直到表等于 $populatedrows。这将等于包含数据的 post 变量的数量。

对我来说情况很奇怪,所以不太确定如何去做。

最佳答案

如果您只想为每个非空的 $_POST 变量创建输入:

    <?php
    foreach($_POST as $key => $value) //$key is e.g 'line_1_20'
    {
        // substr($key, 0, 5) == 'line_' checks if the $key starts with 'line_'
        if((substr($key, 0, 5) == 'line_') && !empty($value))
        {
        ?>
            <tr>
                <td>
                  <input type="text" value="<?php echo $value ?>">
                </td>
            </tr>
        <?php
        }
    }
    ?>

如果你想要更少,那么所有填充的 $_POST:

    <?php
    $count = 0; //count rendered fields
    foreach($_POST as $value)
    {
        if(!empty($value))
        {
        ?>
            <tr>
                <td>
                  <input type="text" value="<?php echo $value ?>">
                </td>
            </tr>
        <?php
        $count++; //increase counter
        }

        if($count == $populatedrows) //if the coutner hits the requested amount break the loop
            break;
    }
    ?>

关于PHP 使用 POST 信息创建表,循环遍历填充的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16190282/

相关文章:

php - 从 MySQL 结果创建层次数组

php - 上传多张图片到mysql数据库

php - Symfony 2 落后于 ubuntu 并且速度太慢

javascript - 悬停时更改图像的解决方案

css - 100%的div宽度并没有占据页面的100%?

JavaScript 和 CSS 类未按预期运行

R:循环自定义 dplyr 函数

php - 如何在Yii中实现表格行拖放排序?

javascript - While 循环增加数字直到高于或等于目标

c# - 在for循环中添加随机生成的数字的总和