nielsv
nielsv

Reputation: 6800

Sort array with objects on property of objects

I would like to sort an array of objects by a property of the specific object. This is my array with objects:

enter image description here

As you can see I have an array $all_studies with 2 objects. How can I now sort on the graduationYear property of the objects? So I would like to have an array with objects and the the order with object 2010 first, then 2014, ... (in this case the order is already correct but this won't always be the same ..).

This is what I've tried but with no succes:

$all_studies = usort($all_studies, "sort_objects_by_graduationyear");

function sort_objects_by_graduationyear($a, $b) {
    if((int)$a->graduationYear == (int)$b->graduationYear){ return 0 ; }
    return ($a->graduationYear < $b->graduationYear) ? -1 : 1;
}

But I just get true back. I've never used the usort function so I don't really know how to work with it. Can someone help me?

Upvotes: 2

Views: 2798

Answers (2)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

You were assigning the value of usort to $all_studies which'll be true and false thus you were not getting the value as desired. In fact you need to just sort the array and print that values and its all done

Try as

usort($all_studies, "sort_objects_by_graduationyear");

function sort_objects_by_graduationyear($a, $b) {
    if((int)$a->graduationYear == (int)$b->graduationYear){ return 0 ; }
    return ($a->graduationYear < $b->graduationYear) ? -1 : 1;
}

print_r($all_studies);

Return Values ¶

Returns TRUE on success or FALSE on failure.

Check Docs

Upvotes: 2

jpclair
jpclair

Reputation: 206

The function usort returns "true" on success. So, good news :).

If you want to check if the sort is done, you only have to check your $all_studies object after the usort.

$status = usort($all_studies, "sort_objects_by_graduationyear");
print_r($all_studies);

Upvotes: 3

Related Questions