second sorting with php usort

别等时光非礼了梦想. 提交于 2019-12-11 06:12:49

问题


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


来源:https://stackoverflow.com/questions/2875601/second-sorting-with-php-usort

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!