Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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] =>
      array(['description'] =>890
            ['valore'] =>444)
      [1] =>
      array(['description'] =>98090
            ['value'] =>77)
) 

I know i can achieve this if my html is like this:

<input type='text' name="someName[0][value]">
<input type='text' name="someName[0][description]">
<input type='text' name="someName[1][value]">
<input type='text' name="someName[1][description]">

My problem is that the input fields are on rows of a table and the user can add/remove as many rows as he want, so i can't have fixed index (or i have to modify the name of the input fields each time a row is added since every time i add a row i clone the upper row in the table)

So what i am asking is one of these two things:

1) is there a way to post data the way i want without specifing an index

2)if not, how can i modify dynamically the new input field so that they have an updated name with the new index?

EDIT - i had alredy tried using name="someName[value][]" and name="someName[description][]" but the output is not the desired one:

array(['terreniOneri'] =>
       array(['descrizione'] =>array([0] =>890
                                      [1] => 98090)
               ['valore'] =>array([0] =>444
                                  [1] =>677)
      ) 

i know i can iterate on this array in php i was just wondering if i could avoid it.

like image 420
Nicola Peluchetti Avatar asked May 20 '11 13:05

Nicola Peluchetti


People also ask

How do you assign a value to an index array?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

Can an array be indexed?

When you want to access selected elements of an array, use indexing. Using a single subscript to refer to a particular element in an array is called linear indexing.

How do you send data to an array?

Arrays can be passed to other methods just like how you pass primitive data type's arguments. To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type.

Can you index an array with string?

Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object.


2 Answers

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 />\n";
        echo "Description: ".$row['description']."<br />\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:

<?php
if (count($_POST['somename']) > 0)
{
    $i = 0;
    foreach ($_POST['somename'] as $row)
    {
        echo "Index $i<br />\n";
        echo "Value: ".$row['value']."<br />\n";
        echo "Description: ".$row['description']."<br />\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 <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>
like image 53
Carlos Campderrós Avatar answered Sep 18 '22 00:09

Carlos Campderrós


Try like this:

<input type='text' name="someNameValue[]">
<input type='text' name="someNameDescription[]">

If the fields are paired, they can be attached by the indexes. So if you have the 10th row, someNameValue[9] and someNameDescription[9] will be a pair. You can merge them.

EDIT: You don't have to write the indexes manually, they will be automatically generated.

<input type='text' name="someName[]">
<input type='text' name="someName[]">
<input type='text' name="someName[]">

and

<input type='text' name="someName[0]">
<input type='text' name="someName[1]">
<input type='text' name="someName[2]">

will give the same result in your post array.

like image 28
Damien Avatar answered Sep 19 '22 00:09

Damien