sort listings, search results, etc
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.
1) If 100% of the results are displayed on the same page, you can do this in the client side code (HTML+JavaScript). There are several ways to do this. Your question is too broad so the best advice on this approach I can give you is to Google "html sortable table" and/or "javascript sortable table".
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);
or
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
<A HREF="/your/cgi/script.php?order_by=column_name1">column_name1</A>
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.
精彩评论