Output from your code is
array(4) {
["name"]=>
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
}
["bday"]=>
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
}
["address"]=>
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
}
["gender"]=>
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
}
}
So it's correct. I cloned once, so I get two arrays of "name", two arrays of "bday" etc.
I guess that you want another format, this is a little trickier I think. Try this:
<button id="clone">Clone</button>
<form method="POST">
<div id="div-container">
<div class="div-clone">
<input data-field="name" name="data[0][name]">
<input data-field="bday" name="data[0][bday]">
<input data-field="address" name="data[0][address]">
<input data-field="gender" name="data[0][gender]">
</div>
</div>
<button type="submit">Submit</button>
</form>
<pre>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
var_dump($_POST);
}
?>
</pre>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var i = 0;
$('button#clone').on('click', () => {
const clone = $('.div-clone:first').clone();
i++;
clone.find('input').each(function() {
const fieldname = $(this).attr('data-field');
$(this).attr('name', 'data[' + i + '][' + fieldname + ']');
});
clone.appendTo($('#div-container'));
});
</script>
This will give you the following output for one clone.
array(1) {
["data"]=>
array(2) {
[0]=>
array(4) {
["name"]=>
string(1) "1"
["bday"]=>
string(1) "1"
["address"]=>
string(1) "1"
["gender"]=>
string(1) "1"
}
[1]=>
array(4) {
["name"]=>
string(1) "2"
["bday"]=>
string(1) "2"
["address"]=>
string(1) "2"
["gender"]=>
string(1) "2"
}
}
}
The field name is exactly the PHP-Array structure. Using name[] is just an array counting up. But I think all four fields should make one entry. So you have to make one entry (named data), make it an array, which is counted up (by "i") and then you add the field name (name, bday etc.)