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

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

I dont think you read what I am saying?
@lzoesch sandbox.onlinephpfunctions.com/code/… See this example. Doesn't this do exactly what you want?
I retract my statement. I assigned the recur_ksort to a variable. I appreciate it, and sorry for the confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.