gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:16:42 26 4
gpt4 key购买 nike

我有以下数组:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com