您將如何對鍵隨機定義且不一致的多維陣列進行排序?
此處的螢屏截圖顯示的是年份,然后是月份。我想按升序排列月份。

我在堆疊溢位和谷歌上發現的所有方法都顯示了類似的方法array_multisort (array_column($array, 'key'), SORT_DESC, $array);,在我看來,它只有在您知道您的密鑰將是什么時才適用。就我而言,我沒有,可能是 1 個月,也可能是 12 個月,它們的順序是隨機的。
與其他方法相同的事情
usort($table, function($a, $b) use ($column) {
return $a[$column] <=> $b[$column];
});
任何有助于更好地理解的幫助都將是一次很好的學習體驗。
最終想要的結果

uj5u.com熱心網友回復:
You need to sort the array by key value. So if you had an array
$year = ["7" => [], "9" => [], "3" => []];
you would go by
ksort($year); // ["3" => [], "7" => [], "9" => []]
See: https://www.php.net/manual/en/function.ksort.php
And a running example: http://sandbox.onlinephpfunctions.com/code/216a48077d871dbd871445013fc838ddb1130bd4
If you need to apply for multidimensional arrays, I suggest you use a recursive function like from this answer: https://stackoverflow.com/a/4501406/5042856
// Note this method returns a boolean and not the array
function recur_ksort(&$array) {
foreach ($array as &$value) {
if (is_array($value)) recur_ksort($value);
}
return ksort($array);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/357419.html
上一篇:PHP陣列總和和分組重復
