Search code examples
javascriptphphtmlsortinghtml-table

Sorting HTML Table by Column Value


I am looking for someone to give me a hand with this problem:

We have a database filled with user's ranks, this data is pulled and put into a table like so (can't post an image):

Name: Rank: Claims: Last Seen:
Test1 Admin 111 Active Now
Test2 Moderator 213 Active Now
Test3 Senior Admin 123 Active Now

IMAGE HERE

We basically want the 'Rank' Column to sort so that 'Senior Admin' is first, 'Admin' second and 'Moderator' last.

I have spent hours looking up ways to sort tables via sql sorting, php array sorting, javascript sorting etc. but cant find anything that doesn't sort alphabetically.

Any help with this is greatly appreciated!


Solution

  • PHP offers a custom sort function called usort. See here for documentation.

    It allows you to compare two objects using a custom comparison function. W3Schools has a good tutorial on how to get started making your own comparison function.

    The usort function takes two parameters: the array you wish to sort, and the custom comparison function. For example, if you have an array of results called $results, you can define your comparison function like so:

    function my_compare($person1, $person2) {
        if($person["rank"] == $person2["rank"]) {
            return 0;
        }
        elseif($person1["rank"] == "Senior Admin") { // Senior admin will always be at the top
            return -1; 
        }
        elseif($person2["rank"] == "Senior Admin") {
            return 1;
        }
        elseif($person1["rank"] == "Admin" && $person2["rank"] == "Moderator") {
            return -1;
        }
        elseif($person1["rank"] == "Moderator" && $person2["rank"] == "Admin") {
            return 1;
        }
        else {
            return 0;
        }
    }
    

    Then, you can apply your sort by calling usort($results, "my_compare");