Question

I want to sort bidimensional associative arrays by a given key, using uasort.

I have tried

function sortBy(&$arr, $key) {
    $cmp = function($a, $b) {
        global $key;
        return $a[$key] < $b[$key] ? -1 :
               $a[$key] == $b[$key] ? 0 : 1;
    };
    return uasort($arr, $cmp);
}

But $key is undefined inside $cmp.

Était-ce utile?

La solution

Try to use this

function sortBy(&$arr, $key) {
    $cmp = function($a, $b) use ($key) {
        return $a[$key] < $b[$key] ? -1 :
           $a[$key] == $b[$key] ? 0 : 1;
    };
    return uasort($arr, $cmp);
}

Autres conseils

This should solve the problem

function sortBy(&$arr, $key) {
    $cmp = function($a, $b) use($key) {
        global $key;
        return $a[$key] < $b[$key] ? -1 :
               $a[$key] == $b[$key] ? 0 : 1;
    };
    return uasort($arr, $cmp);
}

Notice that I added use($key) into the declaration of the nested function. You can find out more here http://www.php.net/manual/en/functions.anonymous.php

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top