I currently have a function which creates an array from a html table the array output is
array:1 [
0 => array:3 [
0 => "Test"
1 => "Test"
2 => "Test"
]
]
Method for creating array from HTML
let convertedIntoArray = [];
$("table#campaign_csv_table tr").each(function () {
let rowDataArray = [];
let actualData = $(this).find('textarea');
if (actualData.length > 0) {
actualData.each(function () {
rowDataArray.push($(this).text());
});
convertedIntoArray.push(rowDataArray);
}
});
How would I modify this array so it looks like this:
array:1 [
0 => array:3 [
"first_name" => "Test"
"last_name" => "Test"
"email" => "Test"
]
HTML table
<table >
<thead>
<tr >
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<td id="table-cells"
><textarea rows="1" cols="50" style="resize: none" required
></textarea>
</td>
<td id="table-cells"
><textarea rows="1" cols="50" style="resize: none" required
></textarea>
</td>
<td id="table-cells" ><textarea rows="1" cols="50" style="resize: none" required
> Invalid Email Address</textarea>
</td>
</tr>
</tbody>
</table>
I've tried using array_values() within PHP but had no luck can anyone see where im going wrong?
CodePudding user response:
You'll have to push an object instead of an array since you want string keys.
Since your input fields aren't named, I'm using my own array let name = ...
to determine the key names based on the index number.
let convertedIntoArray = [];
$("table#campaign_csv_table tr").each(function () {
let rowDataArray = {};
let actualData = $(this).find('textarea');
if (actualData.length > 0) {
actualData.each(function (i) {
let name = ['first_name', 'last_name', 'email'][i]
rowDataArray[name] = $(this).text();
});
convertedIntoArray.push(rowDataArray);
}
});
console.log(convertedIntoArray)