Say you have an unordered multidimensional array and want to order it by two different keys or values depending on priority. Example below does what you want.


Rules



Raw array


$array = [
'Z' => [
'primary' => true,
'age' => 55
],
'C' => [
'primary' => false,
'age' => 60
],
'K' => [
'primary' => true,
'age' => 60
],
'S' => [
'primary' => false,
'age' => 40
],
'F' => [
'primary' => true,
'age' => 60
],
'A' => [
'primary' => true,
'age' => 30
]
];

Aim


$aim =  [
'F' => [
'primary' => true,
'age' => 60
],
'K' => [
'primary' => true,
'age' => 60
],
'Z' => [
'primary' => true,
'age' => 55
],
'A' => [
'primary' => true,
'age' => 30
],
'C' => [
'primary' => false,
'age' => 60
],
'S' => [
'primary' => false,
'age' => 40
]
];

Function


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

return strcmp($b['primary'], $a['primary']);
});

print_r($array);

Result


(
[F] => Array
(
[primary] => 1
[age] => 60
)

[K] => Array
(
[primary] => 1
[age] => 60
)

[Z] => Array
(
[primary] => 1
[age] => 55
)

[A] => Array
(
[primary] => 1
[age] => 30
)

[C] => Array
(
[primary] =>
[age] => 60
)

[S] => Array
(
[primary] =>
[age] => 40
)
)