Home > front end >  Sorting multi-dimensional array by random key
Sorting multi-dimensional array by random key

Time:11-16

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

CodePudding user response:

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);
}
  • Related