0

How would you sort an multidimensional array where the keys are randomly defined and not consistent?

The screenshot here shows the Year, then the months. Id like to have the months order in ascending order.

Everything Ive found on stack overflow and google shows methods like array_multisort (array_column($array, 'key'), SORT_DESC, $array); which is seems to me that its only applicable if you know what your keys are going to be. In my case I don't, it could be 1 month, or 12 and they'll be in random order.

Same thing with other methods as

usort($table, function($a, $b) use ($column) {
    return $a[$column] <=> $b[$column];
});

Any help to better understand would be greatly appreciative as a good learning experience.

End desired result

enter image description here

levi
  • 1,566
  • 3
  • 21
  • 37

1 Answers1

1

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);
}
Daidon
  • 581
  • 1
  • 3
  • 14
  • I dont think you read what I am saying? – levi Nov 16 '21 at 05:45
  • 1
    @lzoesch http://sandbox.onlinephpfunctions.com/code/2874f1274ccbfca27ab3d7e7a0fe8a80b22e8258 See this example. Doesn't this do exactly what you want? – Daidon Nov 16 '21 at 05:46
  • I retract my statement. I assigned the recur_ksort to a variable. I appreciate it, and sorry for the confusion. – levi Nov 16 '21 at 05:50