Sorting array of objects by value

Drupal uses many multidimensional arrays and usually you won't need to do this, or will do it in some theme layer or with views. But I did have a case where I needed to sort out array of entities by score value so I did it this way.

I used uasort or you can also use usort, both should work and properly order arrays, if you want to be sure, maybe use uasort as it is said that it "maintains index association", not sure if this would be needed here.

Anyway First build function that will be used in uasort and then just call it. I was sorting field_collection array of field collection module, but this can be used for any array, just change the object you want to sort ($field_collection_value) and fields that needs to be compared. Also this will sort everything descending (integer/decimal field), if you want it to be ascending just use < instead of >. You can add this helper function inside of your other drupal function

function sortByScore($a, $b){
  if ($a->field_score[LANGUAGE_NONE][0]['value'] == $b->field_score[LANGUAGE_NONE][0]['value']) {
        return 0;
    }
    return ($a->field_score[LANGUAGE_NONE][0]['value'] > $b->field_score[LANGUAGE_NONE][0]['value']) ? -1 : 1;
}
uasort($field_collection_value, 'sortByScore');