If you have to sort an associative array in a very specific order that cannot be described easily with a lambda, PHP’s sort functions do not help a lot.
In this example, a second array contains the keys in the required order. A nice and easy way to do the same thing with just a few lines of code:
|
|
The first array $source_array
is supposed to be the array that should be sorted.
The second array $sort_order
specifies the required order by listing the elements as they should be arranged.
To sort the array, the internal functions array_fill_keys
and array_merge
are quite helpful:
|
|
The result is a sorted array with a ordering as specified in array $sort_order
:
|
|