How to make a PHP table sorting
Learn how to sort a php table with an easy example: use sort() function to order columns in ascending or descending order.
Creating a Table Sorting System with PHP
One way to create a table sorting system with PHP is to use the usort()
function. This function will allow you to sort an array of data by a given criteria. In this example, we'll create a simple table that can be sorted by its column headers. To do this, we'll need to create a function that will take the array of data and sort it in the desired order.
function sortByColumn($array, $columnName, $order) {
// Sort the array based on the given column
usort($array, function($a, $b) use ($columnName, $order) {
if ($a[$columnName] == $b[$columnName]) {
return 0;
}
if ($order == 'asc') {
return ($a[$columnName] < $b[$columnName]) ? -1 : 1;
} else {
return ($a[$columnName] > $b[$columnName]) ? -1 : 1;
}
});
return $array;
}
The above function takes an array of data, the name of the column to sort by, and the desired order (either "asc" or "desc"). It then uses the usort()
function to sort the array in the desired order based on the given column name. Once the array has been sorted, it is returned.
Now that we have the sorting function, we can use it to create the table. We'll start by creating an array of data to use in our table:
// Create an array of data
$data = array(
array('name' => 'John', 'age' => 20),
array('name' => 'Jane', 'age' => 25),
array('name' => 'Bob', 'age' => 30),
);
We can then create the table itself by looping through the array of data and outputting the data into a table. We'll also add a link to each column header that will allow us to sort the data by that column.
echo '<table>';
// Output the table header
echo '<tr>';
echo '<th><a href="?sort=name">Name</a></th>';
echo '<th><a href="?sort=age">Age</a></th>';
echo '</tr>';
// Get the sort order
if (isset($_GET['sort'])) {
$sortOrder = $_GET['sort'];
} else {
$sortOrder = 'name';
}
// Sort the data
$data = sortByColumn($data, $sortOrder, 'asc');
// Output the table rows
foreach ($data as $row) {
echo '<tr>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>' . $row['age'] . '</td>';
echo '</tr>';
}
echo '</table>';
The above code will output a table with two columns (name and age). Each column header has a link that will allow us to sort the data by that column. When the link is clicked, the sortByColumn()
function is called to sort the data in ascending order by the given column.
This is just a basic example of how to create a table sorting system with PHP. You can modify the code to fit your own needs, such as adding a checkbox to toggle between ascending and descending order, or adding additional columns to the table.