Pregunta

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.

¿Fue útil?

Solución

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);
}

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top