首页 > 解决方案 > 需要在 PHP 中发送一个数组

问题描述

我正在尝试将多个值发送到 PHP 表单。这是我用来发送值的表单:

<form id="form1" name="form1" method="POST" action="../WSweb/Factura.php">
    <table width="561" height="79" border="1">
        <tr>
            <td width="30%" height="32">ProductID</td>
            <td width="30%" height="32">SKU</td>
        </tr>
        <?php do { ?>
            <tr>
                <td><?php echo $row_test1['ProductID']; ?>
                    <input
                        type="hidden"
                        name="Product[id][ProductID]"
                        value="<?php echo $row_test1['ProductID']; ?>"
                    />
                </td>
                <td><?php echo $row_test1['SKU']; ?>
                    <input
                        type="hidden"
                        name="Product[id][SKU]"
                        value="<?php echo $row_test1['SKU']; ?>"
                    />
                </td>
            </tr>
        <?php } while ($row_test1 = mysqli_fetch_assoc($test1)); ?>
    </table>

    <input type="submit" value="Update" name="Facturar">
</form>

这是动作文件:

if(isset($_POST['Update']))
{
    $ProductID=$_POST['Product'];
    print_r(json_encode($ProductID));
}

我遇到的问题是当我发送多个值时,例如下表:

ProductID      SKU
103              WH004BI
137              VO007BI

我总是得到这个结果:

{"id":{"ProductID":"137","SKU":"VO007BI"}}

当我真的想得到这样的结果时:

{"id":[{"ProductID":"103","SKU":"WH004BI"},{"ProductID":"137","SKU":"VO007BI"}]}

标签: phphtml

解决方案


你会想做这样的事情:

<form id="form1" name="form1" method="POST" action="../WSweb/Factura.php">
    <table width="561" height="79" border="1">
        <tr>
            <td width="30%" height="32">ProductID</td>
            <td width="30%" height="32">SKU</td>
        </tr>
        <?php $i = 0; ?>
        <?php while ($row_test1 = mysqli_fetch_assoc($test1) { ?>
            <tr>
                <td>
                    <?php echo $row_test1['ProductID']; ?>
                    <input
                        type="hidden"
                        name="Product[id][<?= $i; ?>][ProductID]"
                        value="<?php echo $row_test1['ProductID']; ?>"
                    />
                </td>
                <td>
                    <?php echo $row_test1['SKU']; ?>
                    <input
                        type="hidden"
                        name="Product[id][<?= $i; ?>][SKU]"
                        value="<?php echo $row_test1['SKU']; ?>"
                    />
                </td>
            </tr>
        <?php $i++; ?>
        <?php } ?>
    </table>

    <input type="submit" value="Update" name="Facturar">
</form>

请注意,我已将 a$i = 0放在循环的开头和循环$i++的结尾。

此外,我已将名称更改为以下内容:

name="Product[id][<?= $i; ?>][SKU]"

这将防止您在评论部分遇到的关于格式错误的数组的问题。


推荐阅读