1

This example depends on two keys/values instead of just one unlike many other examples I've seen in Stack-overflow. Apart from sorting array below by primary key, I also would like to sort it by age key so that I can achieve EXPECTED RESULT below. How should I modify CODE below to achieve it? CURRENT RESULT has A-6-6 key misplaced because my code doesn't handle it yet.

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
    ]
];

EXPECTED RESULT

(
    [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);

CURRENT RESULT

As you can see, A-6-6 is not in right place compared to expected result above. So the bigger the age the higher place it should appear.

(
    [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

1 Answer 1

1

I think you can add an extra check for the 'age' key in the uasort when the values for the 'primary' key are equal'.

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

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.