首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >进行多层排序的最佳/最简单方法是什么?

进行多层排序的最佳/最简单方法是什么?
EN

Stack Overflow用户
提问于 2012-09-21 23:51:01
回答 1查看 387关注 0票数 2

我正在编写一个函数,用于对客户端进行多层次排序(在一种排序中进行排序,因为缺少更好的术语)。假设我们有一个具有不同属性的对象列表,例如:

  • 名称-对象名称
  • 类型-对象类型
  • 日期-一些日期属性

假设我想先按时间顺序对列表排序,然后按对象类型排序,然后按字母顺序排序。我该怎么做?

目前,我正在使用usort()传递自己的比较函数,该函数将将上述属性转换为具有不同权重的整数;如果主排序是按日期排序,则将其转换为某个整数,乘以1000,将下一层排序转换为整数(在本例中为类型),再乘以100,然后将其相加,以确定一个对象是否是<或>另一个。

是否有一个更简单/优雅的解决方案?谢谢

编辑:为了澄清,有没有更好的方法来进行多层次的排序,而不把所有的东西都转换成“权重”?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-22 03:54:53

基本上,你想做的是使用一系列的“短路”比较。考虑到上面的标准,一个简单的示例可能如下所示(未经测试):

代码语言:javascript
复制
function mySort($a, $b) {
    if ($a->name < $b->name) {
        return -1;
    }

    if ($a->name > $b->name) {
        return 1;
    }

    // If we get this far, then name is equal, so
    // move on to checking type:
    if ($a->type < $b->type) {
        return -1;
    }

    if ($a->type > $b->type) {
        return 1;
    }

    // If we get this far, then both name and type are equal,
    // so move on to checking date:
    if ($a->date < $b->date) {
        return -1;
    }

    if ($a->date > $b->date) {
        return 1;
    }

    // If we get this far, then all three criteria are equal,
    // so for sorting purposes, these objects are considered equal.
    return 0;
}

不过,正如我所说,这是一个天真的解决方案,而且是非常不可扩展的。我建议使用一个稍微健壮一些的解决方案,在这个解决方案中,您的排序不是硬编码到排序方法中。例如,采用这种方法(未经测试):

代码语言:javascript
复制
// These are the properties to sort by, and the sort directions.
// They use PHP's native SORT_ASC and SORT_DESC constants.
$this->_sorts = [
    'name' => SORT_ASC,
    'type' => SORT_ASC,
    'date' => SORT_ASC
];

// Implemented as a class method this time.
protected function _mySort($a, $b) {
    foreach ($this->_sorts as $property => $direction) {
        if ($a->{$property} < $b->{$property}) {
            return $direction === SORT_ASC ? -1 : 1;
        }

        if ($a->{$property} > $b->{$property}) {
            return $direction === SORT_ASC ? 1 : -1;
        }
    }

    return 0;
}

现在,添加或删除不同的排序字段或排序方向就像添加或修改数组元素一样简单。无需修改代码。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12539528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档