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

标签 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
        )

) 

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

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

当时间戳相同时,如何也按 id 降序对 id 进行排序?

最佳答案

建议是用$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;
    });
}

干杯!

关于php - 使用匿名函数按两个对象属性对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8598040/

相关文章:

php - 将大型 Excel 工作表转换为 Mysql?

php - 调用未定义函数 apache_request_headers()

php - 使用 jquery 添加每个水平和垂直表单输入的值

iphone - 如何在 iPhone 中对 NSMutableArray 值 Aa-Zz 进行排序?

javascript - 如何在纯 JavaScript 的帮助下对表格进行排序和重新生成

mysql - 如何使用 SQL 按每行中出现的第一组数字对列进行排序?

php - Laravel:检查 Controller 上的数据是否为整数

c++ - 如何使数组变量指向不同的数组,有效地将第二个数组的内容复制到第一个数组中?

ruby-on-rails - Mongoid 范围检查数组字段是否包含值

javascript - 从给定数组中删除索引数组