Home » Php » PHP additional parameters to usort

PHP additional parameters to usort

Posted by: admin July 12, 2020 Leave a comment

Questions:

The following code lays within a function which itself lays within a class. Its purpose is to avoid having one sorting function per $filter value :

$GLOBAL['filter'] = $filter;
usort($this->data, function($arr1, $arr2) {
    return ($arr1[$GLOBALS['filter']] > $arr2[$GLOBALS['filter']]) ? 1 : -1;
});

My solution works perfectly fine, but I find it rather inelegant. Would somebody have an idea to acheive the same goal without resorting to the $GLOBALS variable ?

Thanks for your propositions

How to&Answers:

Since you’re using an anonymous function, you can use it as a closure like this:

$filter = <whatever>;
usort($this->data, function($arr1, $arr2) use ($filter) {
    return ($arr1[$filter] > $arr2[$filter]) ? 1 : -1;
});

Answer:

   public function sortList($params, $listToSort)
    {
        if (!isset($listToSort) || !isset($params) || count($params) == 0) {
            return $listToSort;
        }
        foreach ($params as $col => $value) {
            $orderFlag = $value == 'asc' ? 1 : -1;
            usort($listToSort, function ($a, $b) use ($orderFlag, $col) {
                return strcmp($a[$col], $b[$col]) * $orderFlag;
            });
        }
    return $listToSort;
}

Above $params is json eg: {name : ‘asc’, age : ‘desc’} and $listToSort is array of array eg: array(array(‘name’: ‘Himanshu’, age: 22), array(‘name’: ‘Steve’, age: 35))

Place this code in Utils.php of your project as it is a general solution.