I got a form like this
<form>
<input type="text" class="form-control" placeholder="Titel" name="levels[level]">
<input type="text" class="form-control" placeholder="Titel" name="levels[build_time]">
<input type="text" class="form-control" placeholder="Titel" name="levels[level]">
<input type="text" class="form-control" placeholder="Titel" name="levels[build_time]">
</form>
I'd like to have as $_POST output an array like:
Array (
[1] => Array ( [level] => 1 [build_time] => 123 )
[2] => Array ( [level] => 2 [build_time] => 456 )
)
I know I could do something like name="levels[1][build_time]" and so on, but since these elements get added dynamically, it would be hard to add an index. Is there another way?
As suggested, I changed my form. I also included my whole HTML now, because I think I'm missing something here. My HTML now:
<div class="form-group">
<label class="col-md-2">Name(z.B. 1)</label>
<div class="col-md-10">
<input type="text" class="form-control" placeholder="Titel" name="levels[][level]">
</div>
<label class="col-md-2">Bauzeit(In Sekunden)</label>
<div class="col-md-10">
<input type="text" class="form-control" placeholder="Titel" name="levels[][build_time]">
</div>
</div>
<div class="form-group">
<label class="col-md-2">Name(z.B. 1)</label>
<div class="col-md-10">
<input type="text" class="form-control" placeholder="Titel" name="levels[][level]">
</div>
<label class="col-md-2">Bauzeit(In Sekunden)</label>
<div class="col-md-10">
<input type="text" class="form-control" placeholder="Titel" name="levels[][build_time]">
</div>
</div>
The output I get now is:
[levels] => Array (
[0] => Array ( [level] => 1 )
[1] => Array ( [build_time] => 234 )
[2] => Array ( [level] => 2 )
[3] => Array ( [build_time] => 456 )
)
As suggested in your edit, I edited my form and moved the square brackets to the end of the name. The output I get now is:
[levels] => Array (
[level] => Array (
[0] => 1
[1] => 2
)
[build_time] => Array (
[0] => 234
[1] => 456
)
)
I guess that would kind of work, but it still looks complicated. Isn’t there a better way?