我有以下数组:
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;
});
}
干杯!