How do you setup a system where users can sort results or listings by price, distance, relevance, etc...? Such as on YouTube where you can sort by views, relevance, or other options.
The most common approach is to store the table data in a data structure (e.g. JSON array), a JS sorting routine to produce re-sorted array; and have a JS subroutine which populates table cell contents with the contents of the re-sorted array. The original JSON array is printed into the page by the backend PHP script.
There are existing JS scripts/libraries to do this for you, both pure JS as well as YUI and jQuery.
2) Otherwise, you can do this on the back-end, and re-sorting submits a request with "what to sort by" parameter, with the resulting HTML already containing table data which was pre-sorted in your PHP script (or even database query before PHP script got the data). The algorithm is (not written in PHP :)
order_by = get_CGI_parameter("order_by"); data_array = retrieve_data(order_by); execute_view_code(data_array);
data_array = retrieve_data(); sorted_data_array = sort_data(data_array, order_by); execute_view_code(sorted_data_array);
Then, your HTML table has headers which are links in the form of
You would have a table of results with a link at the top of each column (or elsewhere). The link would be one to the page you are in with an added
$_GET variable added to the URL. This variable could be used in a
SELECT query which would use the
ORDER BY option in SQL to sort the data for you before you output it again.