1

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.

1

2 Answers 2

4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.