1
這個例子依賴於兩個鍵/值,而不是像我在堆棧溢出中看到的許多其他例子那樣。除了通過primary
鍵排序數組以外,我還想按age
鍵對它進行排序,以便我可以在下面實現預期結果。我應該如何修改下面的代碼來實現它? CURRENT RESULT有A-6-6
鍵錯位,因爲我的代碼還沒有處理它。使用兩個不同的鍵或值排列多維數組
原始數組
$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
)
)
我不知道它是否匹配你的問題;不過,你可以快速瀏覽一下:http://php.net/manual/en/function.uasort.php#114535 –