keepwalking
keepwalking

Reputation: 2654

Sorting an array using usort and a dynamic generated function

I am using php function usort to sort an array. The custom php function must be generated because its dynamic

$intCompareField = 2;
$functSort = function($a, $b) {
  return ($a[$intCompareField] > $a[$intCompareField])?1:-1;
}

usort($arrayToSort, $functSort);

The $intCompareField in the compare function is null, my guessing is because the $intCompareField was declared outside of the function. Setting global $intCompareField does not seem to work.

Ps: I am using $intCompareField because the array to sort is multidimensional and i want to be able what key in the array to sort.

Upvotes: 1

Views: 1764

Answers (2)

salathe
salathe

Reputation: 51950

While Dor Shemer's answer would suffice, I find it often better to have a function which generates the required comparison function.

$functSort = function ($field) {
    return function($a, $b) use ($field) {
        // Do your comparison here
    };
};

$intCompareField = 2;
usort($arrayToSort, $functSort($intCompareField));

You could make the function in $functSort be a named function (e.g. sort_by_field_factory() or some other appropriate name), there's no requirement for it to be an anonymous function.

Upvotes: 4

dorsh
dorsh

Reputation: 24730

Try adding use, which passes variables from the outer scope to anonymous functions

function($a, $b) use ($intCompareField) {
     return ($a[$intCompareField] > $a[$intCompareField])?1:-1;
}

Upvotes: 3

Related Questions