second sorting with php usort

2019-08-05 08:11发布

问题:

So Ive got a pretty big array of data and need to sort them by two criteria.

There is variable $data['important'] and $data['basic'].

They are simple numbers and I am using uasort to sort $data firstly by important and then by basic.

So

Important | Basic
10        | 8
9         | 9
9         | 7
7         | 9

The usort function is a simple

public function sort_by_important($a, $b) {

        if ($a[important] > $b[important]) {
            return -1;
        } 
        elseif ($b[important] > $a[important]) {
            return 1;
        } 
        else {
            return 0;
        }
    }

How can I re-sort the array to the second variable and keep the Important ordering?

Thanks everyone.

EDIT

How about adding a third sorting option after this even? So Important > Basic > Less

回答1:

You really should use array_multisort(),

// Obtain a list of columns
foreach ($data as $key => $row) {
    $important[$key]  = $row['important'];
    $basic[$key] = $row['basic'];
}

array_multisort($important, SORT_NUMERIC, SORT_DESC,
                $basic, SORT_NUMERIC, SORT_DESC,
                $data);

but if you must use usort():

public function sort_by_important($a, $b) {

    if ($a[important] > $b[important]) {
        return -1;
    } elseif ($b[important] > $a[important]) {
        return 1;
    } else {
        if ($a[basic] > $b[basic]) {
            return -1;
        } elseif ($b[basic] > $a[basic]) {
            return 1;
        } else {
            return 0;
        }
    }
}


回答2:

Why not simply use array_multisort()

public function sort_by_important($a, $b) { 
    if ($a['Important'] > $b['Important']) { 
        return -1; 
    } elseif ($b['Important'] > $a['Important']) { 
        return 1; 
    } else { 
        if ($a['Basic'] > $b['Basic']) { 
            return -1; 
        } elseif ($b['Basic'] > $a['Basic']) { 
            return 1; 
        } else { 
            return 0; 
        }
    } 
} 


标签: php arrays usort