自定义排序数组 [英] custom sort array
本文介绍了自定义排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$array = array(
'list1 - 1',
'list7 - 1',
'list5 - 2',
'list3 - 1'
);
我需要对这个数组进行数字排序.该函数应检查等号后的值以进行排序.
I need sort to this array numerically. The function should check the value after the equal sign for sorting.
结果:
list1 - 1
list7 - 1
list3 - 1
list5 - 2
在以上结果中,直到list[5]
为止,字母或数字的顺序都没有改变.我该怎么办?
In the above result, the order is not changed either alphabetically or numerically until list[5]
. How do I do this?
推荐答案
您似乎想首先搜索尾随数字,但如果它们相同,则希望保留项目的原始顺序.这意味着有更多的思考是必要的,但从本质上讲,这项工作仍然非常简单.
It looks like you want to search firstly on the trailing numbers, but if they are the same then you want to retain the original order of the items. This means a little more thinking is necessary but the job is, in essence, still very simple.
$array = array(
'list1 - 1',
'list7 - 1',
'list5 - 2',
'list3 - 1',
);
function sort_list(&$subject) {
// Get an array of the trailing numbers to use within the callback
$nums = preg_replace('/^.* - (\d+)$/', '$1', $subject);
// Sort values by trailing number or key
uksort($subject, function($a,$b) use ($nums) {
// If numbers are the same, sort by key
if ($nums[$a] === $nums[$b]) {
return $a - $b;
}
// Othwerise sort by numbers
return $nums[$a] - $nums[$b];
});
}
sort_list($array);
var_dump($array);
输出类似:
array(4) {
[0]=>
string(9) "list1 - 1"
[1]=>
string(9) "list7 - 1"
[3]=>
string(9) "list3 - 1"
[2]=>
string(9) "list5 - 2"
}
这篇关于自定义排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文