How can PHP arrays be utilized to reorganize SQL query results for proper HTML table output?
When retrieving data from a SQL query, the results are often in a format that may not be directly suitable for displaying in an HTML table. PHP arrays can be utilized to reorganize the query results into a more structured format that can easily be looped through to generate the HTML table rows and columns.
<?php
// Assuming $results is the array containing the SQL query results
// Initialize an empty array to store the reorganized data
$tableData = [];
// Loop through the query results and reorganize them into a new array
foreach ($results as $result) {
$rowData = [];
$rowData['column1'] = $result['column1'];
$rowData['column2'] = $result['column2'];
// Add more columns as needed
$tableData[] = $rowData;
}
// Output the HTML table
echo '<table>';
echo '<tr><th>Column 1</th><th>Column 2</th></tr>';
foreach ($tableData as $row) {
echo '<tr>';
echo '<td>' . $row['column1'] . '</td>';
echo '<td>' . $row['column2'] . '</td>';
// Add more columns as needed
echo '</tr>';
}
echo '</table>';
?>