سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top