开发者

second sorting with php usort

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

There is variable $data['important'] and $data['basi开发者_如何学JAVAc'].

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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜