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 class="display">
<thead>
<tr class="header">
<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" class="text-danger"><textarea rows="1" cols="50" style="resize: none" required
class="text-danger w-100"> 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?
My Answer:
To modify the array so that it includes keys for each column, you can use the column headers from the table as keys for the array. Here's how you can modify your JavaScript code:
javascript
let convertedIntoArray = [];
$("table#campaign_csv_table tr").each(function () {
let rowDataArray = {};
$(this).find('textarea').each(function (index) {
let columnName = $("table#campaign_csv_table th").eq(index).text().trim().toLowerCase().replace(/\s/g, '_');
rowDataArray[columnName] = $(this).val();
});
convertedIntoArray.push(rowDataArray);
});
In this code snippet, we are creating an object `rowDataArray` instead of an array and using the column headers from the table to create keys for each column in the object. The `columnName` is generated by converting the column header text to lowercase and replacing spaces with underscores.
This should give you the desired array structure with keys for each column.
Rate this post
4 of 5 based on 5144 votesComments