How can a two-dimensional array be used to organize and display data from a MySQL query in PHP when the data needs to be grouped and displayed in a table format?
When organizing and displaying data from a MySQL query in PHP, a two-dimensional array can be used to group and display the data in a table format. Each row of the two-dimensional array represents a record from the MySQL query result, and each column represents a field in the record. By looping through the array, you can easily populate an HTML table with the data.
<?php
// Assuming $result is the result of a MySQL query
$data = array();
// Fetch data from MySQL query and store in a two-dimensional array
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
// Display data in a table format
echo "<table>";
echo "<tr>";
foreach (array_keys($data[0]) as $header) {
echo "<th>$header</th>";
}
echo "</tr>";
foreach ($data as $row) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>$value</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Related Questions
- How can PHP be utilized to efficiently manage and display dynamic content updates on a website?
- What is the purpose of using a nested array in PHP and what are the potential benefits?
- How can the issue of PHP code not executing within a <textarea> tag be resolved, especially when the document has a ".php" extension?