How to sort an array of Objects in Laravel?

Posted 2 months ago by Danieloplata

I'm trying to sort an array of objects, by a property on the objects.

The data structure looks like this:

Array
(
    [0] => stdClass Object
        (
            [ID] => 1
            [name] => 'Test1'
            [score] => 800
        )

    [1] => stdClass Object
        (
            [ID] => 2
            [name] => 'Test2'
            [score] => 200
        )

    [2] => stdClass Object
        (
            [ID] => 3
            [name] => 'Test3'
            [score] => 500
        )

A quick google suggests I should be able to use

public function sortByScore ($a, $b)
{
    return strcmp($a->score, $b->score);
}

$mySortedData = usort($myData, array($this, 'sortByScore'));

This appears to cause my data to be completely replaced with the value true, and subsequently causes my foreach to fail.

Anyone got any idea how I can achieve this?

Please sign in or create an account to participate in this conversation.