PHP-缺少数字“ foreach键”时如何在“ helper array”中对相应位置进行排序和排列

时间:2019-05-17 14:32:02

标签: php arrays sorting

我有这样的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越高(越早)(user102中具有值authority array,因此它在具有值的user6之前{{1}中的3)。

authority array是基于各个参议员投票的用户顺序。还有“参议院议长”。如果您的用户具有相同的结果(array1user6),请根据“总裁”的偏好对其重新排序。

另一个可能的输入是:

user10

这是期望的输出

$arr = [
    "user7" => 15,
    "user11" => 15,
    "user4" => 30,
    "user19" => 36,
    "user10" => 39,
];

$helper = [
    "user4" => 3,
    "user7" => 2,
    "user10" => 4,
    "user11" => 1,
    "user19" => 5,
];

1 个答案:

答案 0 :(得分:2)

一种选择是使用array_keysarray_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
)