Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array using usort and global variable

I'm using usort to sort a multi-dimensional array. It works fine until the key used to sort concatenates a global variable.

var_dump($lang);//OK, outputs 'eng'

function cmp(array $a, array $b) {
    if ($a['name'] < $b['name']) {
        return -1;
    } else if ($a['name'] > $b['name']) {
        return 1;
    } else {
        return 0;
    }
}

function cmp2(array $a, array $b) {
    global $lang;
    var_dump($lang);//null?

    if ($a['name_'.$lang] < $b['name_'.$lang]) {//line: 93
        return -1;
    } else if ($a['name_'.$lang] > $b['name_'.$lang]) {
        return 1;
    } else {
        return 0;
    }
}

usort($platform['Server'], "cmp");//OK
usort($platform['Asset'], "cmp2");//Notice (8): Undefined index: name_ [APP\View\Platforms\view.ctp, line 93]

How can I concatenate the lang variable inside the function passed to usort?

I'm on PHP 5.3.

Also, would there be a way to unify both these functions into one while passing the key to sort on as a parameter?

like image 710
TechFanDan Avatar asked Apr 22 '26 12:04

TechFanDan


1 Answers

If you are using PHP 5.3+, then you can take advantage of anonymous functions:

usort($platform['Asset'], function(array $a, array $b) use($lang){
    if ($a['name_'.$lang] < $b['name_'.$lang]) {
        return -1;
    } else if ($a['name_'.$lang] > $b['name_'.$lang]) {
        return 1;
    } else {
        return 0;
    }
});
like image 68
Rocket Hazmat Avatar answered Apr 24 '26 02:04

Rocket Hazmat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!