What are some common methods for sorting HTML tables in PHP?
When displaying data in an HTML table using PHP, it is common to want to provide the user with the ability to sort the table based on different columns. One way to achieve this is by using JavaScript libraries like DataTables or implementing sorting functionality directly in PHP. Here is an example of how you can implement sorting functionality in PHP for an HTML table:
<?php
// Sample data to display in the table
$data = array(
array('name' => 'John', 'age' => 25),
array('name' => 'Alice', 'age' => 30),
array('name' => 'Bob', 'age' => 20)
);
// Sort the data based on a specific column
usort($data, function($a, $b) {
return $a['age'] - $b['age']; // Sort by age in ascending order
});
// Display the sorted data in an HTML table
echo '<table>';
echo '<tr><th>Name</th><th>Age</th></tr>';
foreach ($data as $row) {
echo '<tr><td>' . $row['name'] . '</td><td>' . $row['age'] . '</td></tr>';
}
echo '</table>';
?>