【问题标题】:Sort and filter based on multiple criteria from REST API call根据来自 REST API 调用的多个条件进行排序和过滤
【发布时间】:2019-04-28 22:18:27
【问题描述】:

我想根据多个条件对从 API 调用收到的数据进行排序,然后对其进行过滤以在 2 个不同的表中显示数据。

这是我现在对数据进行排序的代码,1) 机器->id,2) 日期,3) 排序。

function cmp($a, $b)
{
    if (strtotime($a->date) == strtotime($b->date)){
        return $a->ordering - $b->ordering;
    }
    if ($a->machine->id == $b->machine->id) {
        return strtotime($a->date) - strtotime($b->date);
    } 
    return strcmp($a->machine->id, $b->machine->id);
}
usort($obj, "cmp");

之后,我只过滤具有特定机器->id 的数据以在表中显示该数据:

$machine1 = array_filter($obj, function($object){
    return ($object->machine->id == 1141);
});

$machine2 = array_filter($obj, function($object){
    return ($object->machine->id == 1259);
});

现在 machine1 的表中的数据如下所示,日期排序不正常:

2018-11-26T23:00:00Z - ordering: 1
2018-11-26T23:00:00Z - ordering: 3
2018-11-27T23:00:00Z - ordering: 2
2018-11-27T23:00:00Z - ordering: 3
2018-11-27T23:00:00Z - ordering: 4
2018-11-27T23:00:00Z - ordering: 5
2018-11-25T23:00:00Z - ordering: 1
2018-11-25T23:00:00Z - ordering: 2
2018-11-26T23:00:00Z - ordering: 2
2018-11-27T23:00:00Z - ordering: 1
2018-11-25T23:00:00Z - ordering: 3
2018-11-25T23:00:00Z - ordering: 4
2018-11-25T23:00:00Z - ordering: 5
2018-11-25T23:00:00Z - ordering: 6
2018-11-25T23:00:00Z - ordering: 7
2018-11-25T23:00:00Z - ordering: 8
2018-11-25T23:00:00Z - ordering: 9
2018-11-25T23:00:00Z - ordering: 10
2018-11-25T23:00:00Z - ordering: 11
2018-11-26T23:00:00Z - ordering: 4
2018-11-26T23:00:00Z - ordering: 5
2018-11-26T23:00:00Z - ordering: 6
2018-11-26T23:00:00Z - ordering: 7
2018-11-26T23:00:00Z - ordering: 8
2018-11-26T23:00:00Z - ordering: 9
2018-11-26T23:00:00Z - ordering: 10
2018-11-26T23:00:00Z - ordering: 11
2018-11-26T23:00:00Z - ordering: 12
2018-11-26T23:00:00Z - ordering: 13
2018-11-26T23:00:00Z - ordering: 14
2018-11-26T23:00:00Z - ordering: 15
2018-11-26T23:00:00Z - ordering: 16

我做错了什么?

【问题讨论】:

    标签: php arrays sorting filtering usort


    【解决方案1】:

    发生这种情况是因为您在比较函数中使用了机器 ID,但在您过滤了不同的机器之后。

    想一想:

    1. time = 2015, id = 3, order 2
    2. time = 2016, id = 4, order 3
    3. time = 2013, id = 3, order 3
    

    当比较 1 和 2 订单时,它们会在 2 和 3 上交换,因为 ID 但是你会在 3 之前得到 1,这对你来说是错误的订单(日期...)

    我建议首先将大数组拆分为机器数组:

    $machine1141 = array_filter($obj, function($object){
        return ($object->machine->id == 1141);
    });
    

    然后使用比较函数:

    function cmp($a, $b)
    {
        if (strtotime($a->date) == strtotime($b->date))
            return $a->ordering - $b->ordering;
        return strtotime($a->date) - strtotime($b->date);
    }
    usort($machine1141, "cmp");
    

    希望有帮助!

    【讨论】:

    • 嗨,David,感谢您的快速回复,您的解决方案对我有用,在 return $a->ordering - $b->ordering; 之后只缺少一个 }
    猜你喜欢
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2020-07-05
    • 2020-10-27
    • 2023-02-01
    • 2021-07-13
    相关资源
    最近更新 更多