Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting multi-dimensional array by random key

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading