How to POST data as an indexed array of arrays (without specifying indexes)

后端 未结 2 1151
傲寒
傲寒 2020-12-06 18:42

i\'m having some problem with posting data as an array of array. This is how i\'d like my data to be POSTED:

array(
[\'someName\'] =>
array([0] =>
             


        
2条回答
  •  庸人自扰
    2020-12-06 19:05

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

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

     0)
    {
        foreach ($_POST['somename'] as $row)
        {
            echo "Value: ".$row['value']."
    \n"; echo "Description: ".$row['description']."
    \n"; } }

    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:

     0)
    {
        $i = 0;
        foreach ($_POST['somename'] as $row)
        {
            echo "Index $i
    \n"; echo "Value: ".$row['value']."
    \n"; echo "Description: ".$row['description']."
    \n"; $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

    element. This would be the accompanying js function:

    
    

提交回复
热议问题