且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数据作为数组的索引数组发布(不指定索引)

更新时间:2023-02-18 08:44:15

按照你提出问题的方式去做.如果用户删除某行,您的表单元素将是:

Do it the way you put in the question. If the user removes some row, your form elements would be:

<form action="..." method="post" onsubmit="return reindexer(this);">
    <input type='text' name="someName[0][value]">
    <input type='text' name="someName[0][description]">
    <input type='text' name="someName[2][value]">
    <input type='text' name="someName[2][description]">
</form>

但是在 php 中遍历具有非连续数字索引的数组是没有问题的:使用 foreach 循环.

But there's no problem to traverse an array with non-contiguous numeric indexes in php: use a foreach loop.

<?php
if (count($_POST['somename']) > 0)
{
    foreach ($_POST['somename'] as $row)
    {
        echo "Value: ".$row['value']."<br />
";
        echo "Description: ".$row['description']."<br />
";
    }
}

如果你需要知道每一行的编号作为连续索引(在提供的例子中,第0行仍然是0,但第2行应该是1(因为用户删除了一行),你可以使用一个变量充当计数器:

If you need to know the number of each row as a continous index (in the example provided, row 0 would still be 0, but row 2 should be 1 (as the user deleted one row), you can use a variable acting as a counter:

<?php
if (count($_POST['somename']) > 0)
{
    $i = 0;
    foreach ($_POST['somename'] as $row)
    {
        echo "Index $i<br />
";
        echo "Value: ".$row['value']."<br />
";
        echo "Description: ".$row['description']."<br />
";
        $i++;
    }
}

我认为这种方法比其他解决方案更有意义,因为这样你会有一个项目数组,每个项目都是一个值和一个描述,而不是有两个单独的值和描述数组,并且必须得到来自这两个数组而不是一个数组的项目值.

I think this approach has more sense that the other solutions, as this way you would have an array of items, being each item a value and a description, instead of having two separate arrays of values and descriptions and having to get the values for your item from those two arrays instead of one.

edit:我修改了第一段代码以包含

元素.这将是伴随的 js 函数:

edit: I've modified the first piece of code to include the <form> element. This would be the accompanying js function:

<script type="text/javascript">
function reindexer(frm)
{
    var counter = 0;
    var inputsPerRow = 2;
    for (var idx = 0; idx < frm.elements.length; idx++)
    {
        elm.name = elm.name.replace('%%INDEX%%', counter);
        if (idx % inputsPerRow == 1)
        {
            // only increment the counter (or row number) after you've processed all the
            // inputs from each row
            counter++;
        }
    }
}
</script>