通过两个不同的键或值对多维数组进行排序

时间:2016-01-12 15:48:43

标签: php sorting multidimensional-array

此示例依赖于两个键/值而不是一个键,而不像我在Stack-overflow中看到的许多其他示例。除了按primary键对下面的数组进行排序外,我还希望按age键对其进行排序,以便我可以在下面达到预期结果。我应该如何修改下面的CODE来实现它? CURRENT RESULT的A-6-6键错位,因为我的代码还没有处理它。

ORIGINAL ARRAY

$myarray = [
    'Z-9-0' => [
        'primary' => true,
        'age' => 55
    ],
    'C-7-1' => [
        'primary' => false,
        'age' => 60
    ],
    'K-1-9' => [
        'primary' => true,
        'age' => 60
    ],
    'C-2-1' => [
        'primary' => false,
        'age' => 40
    ],
    'F-6-6' => [
        'primary' => true,
        'age' => 60
    ],
    'A-6-6' => [
        'primary' => true,
        'age' => 30
    ]
];

预期结果

(
    [F-6-6] => Array
        (
            [primary] => 1
            [age] => 60
        )
    [K-1-9] => Array
        (
            [primary] => 1
            [age] => 60
        )
    [Z-9-0] => Array
        (
            [primary] => 1
            [age] => 55
        )
    [A-6-6] => Array
        (
            [primary] => 1
            [age] => 30
        )
    [C-7-1] => Array
        (
            [primary] => 
            [age] => 60
        )
    [C-2-1] => Array
        (
            [primary] => 
            [age] => 40
        )
)

CODE

uasort($myarray, function($a, $b) {
    return strcmp($b['primary'], $a['primary']);
});

print_r($org);

当前结果

如您所见,A-6-6与上述预期结果相比并不合适。因此age越大它应该出现的地方越高。

(
    [A-6-6] => Array
        (
            [primary] => 1
            [age] => 30
        )
    [F-6-6] => Array
        (
            [primary] => 1
            [age] => 60
        )
    [K-1-9] => Array
        (
            [primary] => 1
            [age] => 60
        )
    [Z-9-0] => Array
        (
            [primary] => 1
            [age] => 55
        )
    [C-7-1] => Array
        (
            [primary] => 
            [age] => 60
        )
    [C-2-1] => Array
        (
            [primary] => 
            [age] => 40
        )
)

1 个答案:

答案 0 :(得分:1)

我认为当“主要”键的值相等时,您可以在uasort中为“年龄”键添加额外的检查。

uasort($myarray, function($a, $b) {
    if ($b['primary'] === $a['primary']) {
        return $b['age'] > $a['age'];
    }
    return strcmp($b['primary'], $a['primary']);
});

Demo