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>
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 />
";
}
}
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: 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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…