按多个条件对数组进行排序

时间:2015-01-26 21:27:16

标签: php arrays sorting

我有两个数组:

1- Id人(密钥)和资格(值),此数组具有降序:arsort

   Array
    (
        [61] => 02.30.00
        [95] => 02.30.00
        [19] => 02.01.00
        [131] => 02.00.00
        [58] => 01.60.00
        [97] => 01.50.00
        [76] => 01.40.00
        [20] => 01.30.00
        [112] => 01.10.00
        [42] => 01.10.00            
        [116] => 01.04.00
    }

2- ...和与Id人相关的尝试。

Array
(
    [131] => 1
    [58] => 1
    [61] => 1
    [112] => 2
    [116] => 1
    [42] => 1
    [19] => 1
    [20] => 1
    [76] => 1
    [97] => 1
    [95] => 1
)

我需要维持降序,但是按尝试次数添加升序。我的问题在于这些价值观:

[112] => 01.10.00 | 2
[42]  => 01.10.00 | 1

如何得到这个结果?

Array
(
    [61] => 02.30.00 // 1
    [95] => 02.30.00 // 1
    [19] => 02.01.00 // 1
    [131] => 02.00.00 // 1
    [58] => 01.60.00 // 1
    [97] => 01.50.00 // 1
    [76] => 01.40.00 // 1
    [20] => 01.30.00 // 1
    [42] => 01.10.00 // 1
    [112] => 01.10.00 // 2
    [116] => 01.04.00 // 1
)

编辑:丑陋的解决方案:

    $new = array();
    foreach($qualification as $k => $r)
    {
        $new[$k] = array(
            'qualification'=> $r,
            'attempt'      => $attempt[$k],
            'id'           => $k,       
        );
    }

    foreach ($new as $key => $row)
    {
        $qlf[$key]      = $row['qualification'];
        $att[$key]      = $row['attempt'];
    }
    array_multisort($qlf, SORT_DESC, $att, SORT_ASC, $new);

    $result = array();
    foreach ($new as $row)
    {
        $result[$row['id']] = $row['qualification'];
    }
print_r($result);

1 个答案:

答案 0 :(得分:3)

uksort($qualification, function ($a, $b) use ($qualification, $attempt) {
    return strcmp($qualification[$a], $qualification[$b])
        ?: $attempt[$a] - $attempt[$b];
});

我不完全确定您要对哪个订单进行排序,但上面的代码会这样做;您可能需要切换$a$b才能撤消其中一个或另一个的顺序。