zeckdude zeckdude - 2 months ago 9
PHP Question

How can I sort by column header if clicked on and then sort in reverse order when clicked on again?

I have a table of data that is dynamically being brought in with PHP. I have two Column Headers - Name and Price

I am looking for a PHP script that lets me sort the data by clicking on one of the Column headers, and then when the user clicks on it again, I want it to sort the data in the reverse order. Or if the user clicks on the other column header, it will sort it by that column.

Does anyone know where I can find a PHP script that does that?

Answer

You probably don't need anything too special to do this. Just usort() the array checking whether $_GET['sort'] == 'price', etc to sort the array, and display the array in the table.

at the table heading, provide the link as

<a href="?sort=price">Price</a>

or

<a href="script_name.php?some_params ... &sort=price">Price</a>

you can also use a different SQL statement seeing that it is sort by price.

to do that reverse, you can check whether $_GET['reverse'] == 'true' and do it if so. Then you also have to alter the link so that it links to additional param "reverse=false".

you can also check out natsort() which is sometimes a more sensible way to sort the data.

Another way is to use Javascript, but obviously it will only work for users who didn't turn Javascript off.