3

我有以下帖子变量:

$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 变量的数量。

对我来说很奇怪的情况,所以不知道该怎么做。

4

4 回答 4

2

如果您只想为每个非空 $_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;
    }
    ?>
于 2013-04-24T11:26:15.507 回答
1

你可以迭代你的变量名,有点难看:-) http://php.net/manual/en/language.variables.variable.php

只需做每一个并测试isset(),如果是这样输出它。

例如,您可以嵌套几个 for 循环来生成索引 (1,2,3) 和 (9, 12, 15, 18, 21)。然后得到你的变量

$var_name = '$line_' . $i . '_' . $j;
echo ${$var_name};

您必须在 $j 的前导零中填充 9 -> 09

您可能会考虑遍历发布数据,但如果您更改发送到页面的发布数据的数量或顺序,您的代码就会损坏。

如果数据的顺序不适合您的表,请将其放入数组中,然后再进行表写入。

于 2013-04-24T11:09:23.473 回答
1

尝试这个:

    <table>
    <?php for ($i=1; $i<=$populatedrows; $i++)
      {
       if(isset($_POST[$i])) {
    ?>
         <tr>
           <td>
             <input type="text" value="<?php echo $_POST[$i] ?>">
           </td>
        </tr>
    <?php }
} ?>
    </table>
于 2013-04-24T11:15:52.837 回答
1

试试这个?

<table>
<?php for ($i=1; $i<=$populatedrows; $i++) : 
if (!empty($populatedrows)) continue;
?>
  <tr>
     <td>
       <input type="text" value="//first post with information//">
     </td>
  </tr>
<?php endfor; ?>
</table>
于 2013-04-24T11:18:53.853 回答