我有这样的array1
:
[user2] => 27
[user3] => 30
[user4] => 33
[user5] => 36
[user6] => 39
[user10] => 39
[user12] => 42
使用第二个数组(辅助程序authority
):
[user2] => 6
[user3] => 7
[user4] => 1
[user5] => 4
[user6] => 3
[user10] => 2
[user12] => 5
我想这样对array1
进行排序
[user2] => 27
[user3] => 30
[user4] => 33
[user5] => 36
[user10] => 39 // user10 goes before user6
[user6] => 39
[user12] => 42
算法是:当array1
中的行具有相同的值时,选中authority array
并根据其对相同值的行重新排序。值越低,排序后的array1
越高(越早)(user10
在2
中具有值authority array
,因此它在具有值的user6
之前{{1}中的3
)。
authority array
是基于各个参议员投票的用户顺序。还有“参议院议长”。如果您的用户具有相同的结果(array1
和user6
),请根据“总裁”的偏好对其重新排序。
另一个可能的输入是:
user10
这是期望的输出
$arr = [
"user7" => 15,
"user11" => 15,
"user4" => 30,
"user19" => 36,
"user10" => 39,
];
$helper = [
"user4" => 3,
"user7" => 2,
"user10" => 4,
"user11" => 1,
"user19" => 5,
];
答案 0 :(得分:2)
一种选择是使用array_keys
和array_flip
获取订单数组。使用uksort
根据order
$arr = ....
$helper = ...
$order = array_flip(array_keys( $helper ));
uksort ( $arr , function( $a , $b ) use ( $order, $arr, $helper ) {
if ( $arr[$a] != $arr[$b] ) return $order[$a] - $order[$b];
return $helper[$a] - $helper[$b];
});
更新:
$arr = [
"user7" => 15,
"user11" => 15,
"user4" => 30,
"user19" => 36,
"user10" => 39,
];
$helper = [
"user4" => 3,
"user7" => 2,
"user10" => 4,
"user11" => 1,
"user19" => 5,
];
uksort ( $arr , function( $a , $b ) use ( $arr, $helper ) {
if ( $arr[$a] != $arr[$b] ) return $arr[$a] - $arr[$b];
return $helper[$a] - $helper[$b];
});
这将导致:
Array
(
[user11] => 15
[user7] => 15
[user4] => 30
[user19] => 36
[user10] => 39
)