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

Pee*_*Haa 16 php arrays sorting

我有以下数组:

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

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

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

) 
Run Code Online (Sandbox Code Playgroud)

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

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

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

And*_*ren 18

建议是使用$ 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;
    });
}
Run Code Online (Sandbox Code Playgroud)

然后用它来调用它

sort_comments_by_timestamp($unsorted_array,array("timestamp","id"));
Run Code Online (Sandbox Code Playgroud)

如果你想让它使用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;
    });
}
Run Code Online (Sandbox Code Playgroud)

干杯!