Drupal 8 has a built-in class which allows to sort (multidimensional) arrays very easily.
You can use this class like this:
uasort($form['elements'], [ '\Drupal\Component\Utility\SortArray', 'sortByWeightProperty' ]);
The first argument is the array to be sorted and the second is the method (algorithm) to use to sort the array.
Drupal includes following sorting methods:
- sortByWeightElement: Sorts a structured array by the 'weight' element
- sortByWeightProperty: Sorts a structured array by the '#weight' property
- sortByTitleElement: Sorts a structured array by the 'title' key
- sortByTitleProperty: Sorts a structured array by the '#title' property