使用匿名函数按两个对象属性对数组进行排序

2022-08-30 19:50:57

我有以下数组:

Array
(
    [0] => stdClass Object
        (
            [timestamp] => 1
            [id] => 10
        )

    [1] => stdClass Object
        (
            [timestamp] => 123
            [id] => 1
        )

    [2] => stdClass Object
        (
            [timestamp] => 123
            [id] => 2
        )

) 

我目前正在使用以下代码按时间戳属性对数组进行排序:

function sort_comments_by_timestamp(&$comments, $prop)
{
    usort($comments, function($a, $b) use ($prop) {
        return $a->$prop < $b->$prop ? 1 : -1;
    });
}

当时间戳相同时,我如何通过降序对id进行排序?id


答案 1

建议发送一个带有$props

function sort_comments_by_timestamp(&$comments, $props)
{
    usort($comments, function($a, $b) use ($props) {
        if($a->$props[0] == $b->$props[0])
            return $a->$props[1] < $b->$props[1] ? 1 : -1;
        return $a->$props[0] < $b->$props[0] ? 1 : -1;
    });
}

然后用

sort_comments_by_timestamp($unsorted_array,array("timestamp","id"));

如果您希望它使用X个$props则可以在usort内部创建一个循环,始终将属性与其在数组中的先前属性进行比较,如下所示:

function sort_comments_by_timestamp(&$comments, $props)
{
    usort($comments, function($a, $b) use ($props) {
        for($i = 1; $i < count($props); $i++) {
            if($a->$props[$i-1] == $b->$props[$i-1])
                return $a->$props[$i] < $b->$props[$i] ? 1 : -1;
        }
        return $a->$props[0] < $b->$props[0] ? 1 : -1;
    });
}

干杯!


答案 2
function sort_comments_by_timestamp(&$comments, $prop)
{
    usort($comments, function($a, $b) use ($prop) {
        if ($a->$prop == $b->$prop)
          return $b->id - $a->id;
        else
          return $a->$prop < $b->$prop ? 1 : -1;
    });
}

上述内容首先按参数排序,然后按 排序。$propid