phparrayssortingmultidimensional-arraydynamic

Sort a 2d array by a column and obey a dynamic direction variable


I have an array and i want to sort it by value of key [min] (0.2, 0.86 ...) in a desc order. Here is an array:

Array
(
    [0] => Array
        (
            [p1_first_res_avalue] => 0.72413793103448
            [p1_rating_lang_avalue] => 0.2
            [p1_ps_res_avalue] => 0.79310344827586      
            [pid] => 0
            [p1_discipline_e_avalue] => 0.77777777777778
            [p1_rating_lang] => 46
            [p1_first_res] => 59
            [p1_ps_res] => 57
            [p1_discipline_e] => 86
            [min] => 0.2
        )

    [1] => Array
        (
            [p1_discipline_e] => 81
            [p1_first_res] => 55
            [p1_rating_lang] => 38
            [p1_ps_res] => 48
            [p1_discipline_e_avalue] => 1
            [pid] => 1
            [p1_first_res_avalue] => 0.86206896551724
            [p1_rating_lang_avalue] => 1
            [p1_ps_res_avalue] => 1
            [min] => 0.86
        )

   [2] => Array
        (
            [p1_discipline_e] => 81
            [p1_first_res] => 55
            [p1_rating_lang] => 38
            [p1_ps_res] => 48
            [p1_discipline_e_avalue] => 1
            [pid] => 1
            [p1_first_res_avalue] => 0.86206896551724
            [p1_rating_lang_avalue] => 1
            [p1_ps_res_avalue] => 1
            [min] => 0.3
        )
...
)

I've tried to use uasort function, but I can't get access to [min] value of array to compare it. That's what i try ($res is an array, need to sort):

$sortd = 'down';
$f = function($a, $b) use ($sortd) {
        if (($sortd) == 'down') {
            if ($a['min'] == $b['min']) return 0;
            return ($a['min'] > $b['min']) ? -1 : 1;
        }
        else {

        }
    };

foreach ($res as $k => $v) {
    uasort($res[$k], $f);
}

Please, any ideas how to solve the problem?


Solution

  • Your problem seems to be that you're trying to apply the sorting function to each element of the array individually, instead of the array as a whole.

    Instead of

    foreach ($res as $k => $v) {
        uasort($res[$k], $f);
    }
    

    Try just

    uasort($res, $f);