views:

105

answers:

1

I'd like to have a form's data arrive on the server ordered in a specific format as an array. Presently, I have the following form elements which may appear numerous times in my markup:

...
<tr>
  <td><p>Friend's Name:</p></td>
  <td><p><input type="text" name="friends[name][]" /></p></td>
  <td><p>Friend's Email:</p></td>
  <td><p><input type="text" name="friends[email][]" /></p></td>
  <td><p><input type="button" value="+" class="addOne" /></td>
</tr>
...

When submitted, the result appears like this:

[friends] => Array
  (
    [name] => Array
    (
      [0] => John Doe
      [1] => Jane Doe
    )
    [email] => Array
    (
      [0] => [email protected]
      [1] => [email protected]
    )
  )

I can use this array just fine, but I'm curious if it's possible to have the same data appear in the form of the following array example:

[friends] => Array
  (
    [0] => Array
    (
      [name] => John Doe
      [email] => [email protected]
    )
    [1] => Array
    (
      [name] => Jane Doe
      [email] => [email protected]
    )
  )

I understand that I could use the names with specific indexes to acheive this, like this:

friends[0][name] and friends[0][email]

But I'm curious if I can achieve the same result without having to dynamically write new names for the form elements.

+2  A: 

My first thought was to use name="friends[][name]" instead of name="friends[name][]"
Then, I quickly realised the indices will be incremented too, to give out friends[0][name] and friends[1][email]

I guess, the only feasible solution I can think of is to manipulate the POST data and rearrange them like you want them to be, something like:

$newFriends=array();
foreach($_POST["friends"] as $k1 => $v1){
  foreach($v1 as $k2 => $v2){
    $newFriends[$k2][$k1]=$v;
  }
}

$newFriends should have the structure you are looking for

Ofcourse, you would need to add the isset() and is_array() checks as required... and be wary of the fact that some values may be overwritten if the data is not POST-ed in the sequence that you are expecting...

pǝlɐɥʞ
That is the only solution I thought of as well. That, or dynamically re-write the field names with javascript, but that falls apart in the absence of javascript. Thank you for the attention though :)
Jonathan Sampson