Monday 3 September 2018

PHP - Sorting Tables

So I am wanting to sort an array depending on what the user selects, I have managed to get it all working (With a little help from you guys) and now I am trying to clean up the code. This is what i've got

//Global Sorting Functions (For Rows to Columns)
//Function to sort up or down
function cmpdwn($a, $b) {
    return strcasecmp($a["Name"], $b["Name"]);
}

function cmpup($a, $b, $c) {
    return strcasecmp($b[$c], $a[$c]);
}

//Name Ordering Function ---------------------------------
function nameorder($data) {
    //If Up sorts Assending if Down Decending
    if ($_POST['Sortby'] == "NameDown") {
        uasort($data, "cmpdwn");
    } else {
        uasort($data, "cmpup");
    }

    $nameorder = array();
    $count = 0;
    while (list($key, $value) = each($data)) {
        $nameorder[$count] = $key;
        $count++;
    }
    return $nameorder;
}

This creates an array for an order to print the data in name order, I will be repeating this for email too and others. What i wanted to do is re-use the "cmp" function by putting more than $a and $b into (i.e. $c = "Name" then i can put in "Email" or what ever // cmpup as example). But to from the little i know is that this function is declaring an argument for uasort and i don't send variables into it. Is there a way to do so or is it a case of re writing the function repeatedly
Thanks And Big Love

Try to make object
class MyComparator {

    private $key;

    function __construct($key) {
        $this->key = $key;
    }

    function compare($a, $b) {
        return strcasecmp($b[$this->key], $a[$this->key]);
    }

    public function setKey($key) {
        $this->key = $key;
    }
}

And use it
$compararor = new MyComparator("Name");

usort($data, array($compararor, "compare"));

OR in php >= 5.3.0. you can use __invoke() method
class MyComparator {

    private $key;

    function __construct($key) {
        $this->key = $key;
    }

    function __invoke($a, $b) {
        return strcasecmp($b[$this->key], $a[$this->key]);
    }

    public function setKey($key) {
        $this->key = $key;
    }
}

And simple call it with
$compararor = new MyComparator("Name");

usort($data, $compararor);

0 comments:

Post a Comment