使用 php usort 进行第二次排序

blu*_*iel 2 php arrays usort

所以我有相当大的数据数组,需要按两个标准对它们进行排序。

存在变量$data['important']$data['basic']

它们是简单的数字,我使用 uasort $data首先按重要排序,然后按基本排序。

所以

Important | Basic
10        | 8
9         | 9
9         | 7
7         | 9
Run Code Online (Sandbox Code Playgroud)

usort 函数很简单

public function sort_by_important($a, $b) {

        if ($a[important] > $b[important]) {
            return -1;
        } 
        elseif ($b[important] > $a[important]) {
            return 1;
        } 
        else {
            return 0;
        }
    }
Run Code Online (Sandbox Code Playgroud)

如何将数组重新排序为第二个变量并保持重要顺序?

感谢大家。

编辑

在这之后添加第三个排序选项怎么样?非常重要 > 基本 > 更少

ken*_*ytm 5

你真的应该使用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);
Run Code Online (Sandbox Code Playgroud)

但如果你必须使用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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)