How PHP handles 2 dimensional array HTML form input while using Laravel

1.2k views Asked by At

I am using Laravel 5 to develop an HTML form which takes a 2 dimensional array as input. The purpose is to store some contact persons and the input fields for each contact person can be appended or removed by JQuery dynamically.

I would like to use the empty bracket [] so that there is no need to maintain an index. So I have tried 2 cases of HTML form input code. Below are simplified examples:

Case 1:

Person 1:
<input type="text" name="contacts[][surname]">
<input type="text" name="contacts[][first_name]">
<input type="checkbox" name="contacts[][VIP]">

Person 2:
<input type="text" name="contacts[][surname]">
<input type="text" name="contacts[][first_name]">
<input type="checkbox" name="contacts[][VIP]">

But the array I checked using die dump i.e. dd($request->input('contacts')); returned:

array:4 [
  0 => array:1 ["surname" => "Some Value" ]
  1 => array:1 ["first_name" => "Some Value" ]
  2 => array:1 ["surname" => "Some Value" ]
  3 => array:1 ["first_name" => "Some Value" ]
]

Let's forget the checkbox input for now as it does not return anything at all when it is not checked. Having said that, I have included it here in case it is the source of the problem.

Case 2

Person 1:
<input type="text" name="contacts[surname][]">
<input type="text" name="contacts[first_name][]">
<input type="checkbox" name="contacts[VIP][]">

Person 2:
<input type="text" name="contacts[surname][]">
<input type="text" name="contacts[first_name][]">
<input type="checkbox" name="contacts[VIP][]">

Die dump i.e. dd($request->input('contacts')); returns below:

array:2 [
  "surname" => array:2 [
    0 => "Some Value"
    1 => "Some Value"
  ]
  "first_name" => array:2 [
    0 => "Some Value"
    1 => "Some Value"
  ]
]

What I want

This brings us to the question. This is my desired outcome:

array:2 [
  0 => array:2 [
    "surname" => "Some Value"
    "first_name" => "Some Value"
  ]
  1 => array:2 [
    "surname" => "Some Value"
    "first_name" => "Some Value"
  ]
]

Is there a way to do this, and if yes, how do I achieve it? Does this mean I must maintain an index?

1

There are 1 answers

0
dlopez On

Try this.

Person 1:
<input type="text" name="contacts[0][surname]">
<input type="text" name="contacts[0][first_name]">
<input type="checkbox" name="contacts[0][VIP]">

Person 2:
<input type="text" name="contacts[1][surname]">
<input type="text" name="contacts[1][first_name]">
<input type="checkbox" name="contacts[1][VIP]">