Search code examples
phparrayssortingobjectmultidimensional-array

Sort an array of objects by a property in a descending direction


I am trying to sort an associative array which has multiple vales per entry.

For example

[0] => stdClass Object ( [type] => node [sid] => 158 [score] => 0.059600525242489 )
[1] => stdClass Object ( [type] => node [sid] => 247 [score] => 0.059600525242489 )

I want the array sorted by 'score' (highest score is first index)

How would I do this?


Solution

  • Use the usort function with this comparison function:

    function cmpByScore($a, $b) {
        if ($a['score'] == $b['score']) {
            return 0;
        }
        return $a['score'] > $b['score'] ? 1 : -1;
    }
    
    usort($array, 'cmpByScore');