我目前正在使用数组和排序。我使用通常的传统方法来组织数组。但是,我也发现了uasort()
以及它如何允许使用用户定义的比较函数对数组进行排序并保持索引关联。应用uasort
并根据用户定义顺序对下面的数组进行排序的最佳方法是什么?
所需订单Principal, Teacher, Security, BusDriver, Maintanance
:
array(8) {
[0]=>
object(stdClass)#23019 (9) {
["id"]=>
int(1599874)
["firstName"]=>
string(3) "Jim"
["lastName"]=>
string(6) "Turner"
["position"]=>
string(9) "Principal"
}
[1]=>
object(stdClass)#23034 (9) {
["id"]=>
int(14398838)
["firstName"]=>
string(7) "Michael"
["lastName"]=>
string(6) "Watson"
["position"]=>
string(9) "Principal"
}
[2]=>
object(stdClass)#23038 (9) {
["id"]=>
int(17398661)
["firstName"]=>
string(8) "Jermaine"
["lastName"]=>
string(4) "Shaw"
["position"]=>
string(7) "Teacher"
}
[3]=>
object(stdClass)#23003 (9) {
["id"]=>
int(17398683)
["firstName"]=>
string(5) "Maria"
["lastName"]=>
string(6) "Garcia"
["position"]=>
string(7) "Teacher"
}
[4]=>
object(stdClass)#23020 (9) {
["id"]=>
int(17398686)
["firstName"]=>
string(5) "Jacob"
["lastName"]=>
string(5) "Smith"
["position"]=>
string(7) "Teacher"
}
[5]=>
object(stdClass)#23021 (9) {
["id"]=>
int(22398843)
["firstName"]=>
string(4) "Alex"
["lastName"]=>
string(4) "Hood"
["positionUsed"]=>
string(8) "Security"
}
[6]=>
object(stdClass)#23036 (9) {
["id"]=>
int(13398706)
["firstName"]=>
string(4) "Jose"
["lastName"]=>
string(8) "Bautista"
["position"]=>
string(9) "BusDriver"
}
[7]=>
object(stdClass)#23029 (9) {
["id"]=>
int(12398646)
["firstName"]=>
string(6) "Travis"
["lastName"]=>
string(9) "Dickerson"
["position"]=>
string(11) "Maintenance"
}
}
代码:
$staff1 = [
[
'id' => 1599874,
'firstName' => 'Jim',
'lastName' => 'Turner',
'position' => 'Principal',
],
[
'id' => 12398646,
'firstName' => 'Travis',
'lastName' => 'Dickerson',
'position' => 'Maintanance',
],
[
'id' => 17398683,
'firstName' => 'Maria',
'lastName' => 'Garcia',
'position' => 'Teacher',
],
[
'id' => 17398686,
'firstName' => 'Jacob',
'lastName' => 'Smith',
'position' => 'Teacher',
],
[
'id' => 13398706,
'firstName' => 'Jose',
'lastName' => 'Bautista',
'position' => 'BusDriver',
],
[
'id' => 14398838,
'firstName' => 'Michael',
'lastName' => 'Watson',
'position' => 'Principal',
],
[
'id' => 22398843,
'firstName' => 'Alex',
'lastName' => 'Hood',
'position' => 'Security',
],
];
如果数组具有较小的成员集仍然输出相同的顺序:
$staff2 = [
[
'id' => 1599874,
'firstName' => 'Jim',
'lastName' => 'Turner',
'position' => 'Principal',
],
[
'id' => 12398646,
'firstName' => 'Travis',
'lastName' => 'Dickerson',
'position' => 'Maintenance',
],
[
'id' => 17398683,
'firstName' => 'Maria',
'lastName' => 'Garcia',
'position' => 'Teacher',
],
[
'id' => 13398706,
'firstName' => 'Jose',
'lastName' => 'Bautista',
'position' => 'BusDriver',
],
[
'id' => 22398843,
'firstName' => 'Alex',
'lastName' => 'Hood',
'position' => 'Security',
],
];
答案 0 :(得分:0)
在每个“位置”值(Principal,Teacher,Security,BusDriver,Maintanance)之前添加一个数值,并使用usort或uasort在callbkack中使用substr获取第一个值,或者使用preg_match获取前面的数字,如果您将来使用可能需要使用超过10个前缀数字,然后修剪它们。
这是一个肮脏的修复,可能有人会给你一个更好的解决方案,但这是第一个出现在我心中的。