我已经看了很多关于SO的例子,但是我无法找到解决这个问题的方法。我有一个大型数组,我需要用2个元素对它进行排序。
首先,通过自定义顺序中的优先级字段:S1,S2,S3,S4,S5,D,NS
其次,将数组中的2个字段加在一起。 (这一点有效。)
我已经制作了一个排序功能,它将按上述两种方式排序,但是,它在S1-S5之前对D和NS进行排序,因为D首先按字母顺序排列。 - 因此我需要定义一个包含我想要排序的自定义顺序的数组。请任何人帮忙吗?
我使用的功能是:
function compdaily($a, $b) {
if ($a['Priority'] == $b['Priority'])
{
return ($a['Value1'] + $a['Value2']) < ($b['Value1'] + $b['Value2']);
}
return strcmp($a['Priority'], $b['Priority']);
}
然后我以这种方式调用上面的函数:
usort($Array, 'compdaily');
以此顺序显示项目:
Array
(
[0] => Array
(
[SomeID] => 1234
[Priority] => D
[Value1] => 250
[Value2] => 100
)
[1] => Array
(
[SomeID] => 456
[Priority] => NS
[Value1] => 250
[Value2] => 100
)
[2] => Array
(
[SomeID] => 124
[Priority] => S1
[Value1] => 200
[Value2] => 200
)
[3] => Array
(
[SomeID] => 1235
[Priority] => S1
[Value1] => 100
[Value2] => 100
)
[4] => Array
(
[SomeID] => 1230
[Priority] => S2
[Value1] => 250
[Value2] => 100
)
[5] => Array
(
[SomeID] => 123495
[Priority] => S3
[Value1] => 250
[Value2] => 100
)
[6] => Array
(
[SomeID] => 123498
[Priority] => S3
[Value1] => 100
[Value2] => 100
)
[7] => Array
(
[SomeID] => 12345
[Priority] => S4
[Value1] => 250
[Value2] => 100
)
)
但是,我按此顺序需要它们:
Array
(
[0] => Array
(
[SomeID] => 124
[Priority] => S1
[Value1] => 200
[Value2] => 200
)
[1] => Array
(
[SomeID] => 1235
[Priority] => S1
[Value1] => 100
[Value2] => 100
)
[2] => Array
(
[SomeID] => 1230
[Priority] => S2
[Value1] => 250
[Value2] => 100
)
[3] => Array
(
[SomeID] => 123495
[Priority] => S3
[Value1] => 250
[Value2] => 100
)
[4] => Array
(
[SomeID] => 123498
[Priority] => S3
[Value1] => 100
[Value2] => 100
)
[5] => Array
(
[SomeID] => 12345
[Priority] => S4
[Value1] => 250
[Value2] => 100
)
[6] => Array
(
[SomeID] => 1234
[Priority] => D
[Value1] => 250
[Value2] => 100
)
[7] => Array
(
[SomeID] => 456
[Priority] => NS
[Value1] => 250
[Value2] => 100
)
)
我尝试过使用以下示例:Sort an array by multiple keys in a certain order 但是我无法将其与上述工作结合起来。
答案 0 :(得分:0)
不是直接在排序中使用$a['Priority']
,而是可以使用查找表来获取实际订单
类似......
$mapp = array('S1'=>1, 'S2'=>2, 'S3'=>3, 'S4'=>4, 'S5'=>5, 'D'=>6, 'NS'=>7);
function compdaily($a, $b) {
global $mapp;
...
return ($mapp[$a['Priority']] < $mapp[$b['Priority']]);
}
(if语句不需要更改,因为可以直接比较字符串是否相等)