使用PHP usort进行第二次排序 [英] second sorting with php usort

查看:72
本文介绍了使用PHP usort进行第二次排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有大量数据,需要按两个条件对它们进行排序.

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

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

它们是简单的数字,我正在使用uasort进行排序 $ data 首先是重要的,然后是基本的.

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

所以

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

usort函数很简单

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?

谢谢大家.

编辑

在此之后添加第三个排序选项又如何呢?非常重要>基本>更少

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

推荐答案

您确实应该使用 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;
        }
    }
}

这篇关于使用PHP usort进行第二次排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆