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
Sorting functions in PHP are currently unstable, which means that the order of “equal” elements is not guaranteed.
The usort() function in PHP sorts a given array by using a user-defined comparison function.
The usort() function is an inbuilt function in PHP which is used to sort the array of elements conditionally with a given comparator function. The usort() function can also be used to sort an array of objects by object field.
The uasort() function sorts an array by values using a user-defined comparison function. Tip: Use the uksort() function to sort an array by keys using a user-defined comparison function.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With