1

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

有变量$data['important']$data['basic']

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

所以

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

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

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

感谢大家。

编辑

在此之后添加第三个排序选项怎么样?如此重要>基本>少

4

2 回答 2

4

你真的应该使用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);

但如果你必须使用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;
        }
    }
}
于 2010-05-20T16:06:31.140 回答
2

为什么不简单地使用 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; 
        }
    } 
} 
于 2010-05-20T16:04:30.070 回答