php – 使用匿名函数使用两个对象属性排序数组
发布时间:2020-05-29 03:16:53 所属栏目:PHP 来源:互联网
导读:我有以下数组: Array( [0] = stdClass Object ( [timestamp] = 1 [id] = 10 ) [1] = stdClass Object ( [timestamp] = 123 [id]
|
我有以下数组: 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进行排序? 建议使用$道具发送一个数组function sort_comments_by_timestamp(&$comments,$props)
{
usort($comments,$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数量的$道具,你可以在usort中做一个循环,总是把一个属性与它的前面的属性进行比较: function sort_comments_by_timestamp(&$comments,$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;
});
}
干杯! (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
