How can PHP be used to implement sorting functionality in a table by clicking on column headers?
To implement sorting functionality in a table by clicking on column headers, you can use PHP to dynamically generate the sorted table data based on the column header clicked. This can be achieved by passing the column name and sort order as parameters in the URL, then sorting the data accordingly in the PHP script before displaying it in the table.
<?php
// Sample data array
$data = array(
array('id' => 1, 'name' => 'Alice', 'age' => 25),
array('id' => 2, 'name' => 'Bob', 'age' => 30),
array('id' => 3, 'name' => 'Charlie', 'age' => 20)
);
// Get sorting parameters from URL
$sortBy = isset($_GET['sortBy']) ? $_GET['sortBy'] : 'id';
$sortOrder = isset($_GET['sortOrder']) ? $_GET['sortOrder'] : 'asc';
// Sort data based on column header clicked
usort($data, function($a, $b) use ($sortBy, $sortOrder) {
if ($sortOrder == 'asc') {
return $a[$sortBy] <=> $b[$sortBy];
} else {
return $b[$sortBy] <=> $a[$sortBy];
}
});
// Display sorted table
echo '<table>';
echo '<tr><th><a href="?sortBy=id&sortOrder=' . ($sortBy == 'id' && $sortOrder == 'asc' ? 'desc' : 'asc') . '">ID</a></th><th><a href="?sortBy=name&sortOrder=' . ($sortBy == 'name' && $sortOrder == 'asc' ? 'desc' : 'asc') . '">Name</a></th><th><a href="?sortBy=age&sortOrder=' . ($sortBy == 'age' && $sortOrder == 'asc' ? 'desc' : 'asc') . '">Age</a></th></tr>';
foreach ($data as $row) {
echo '<tr><td>' . $row['id'] . '</td><td>' . $row['name'] . '</td><td>' . $row['age'] . '</td></tr>';
}
echo '</table>';
?>
Keywords
Related Questions
- How can one round numbers in PHP to a specific number of decimal places?
- In PHP, how can the display of links be controlled to prevent redundancy and ensure that only authorized users can access certain folders and files?
- How can PHP beginners ensure that the correct form data is included in the email message for online shop orders?