2

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?

3
  • see link Commented Jun 8, 2015 at 11:48
  • usort sorts in place, it does not return the result. See the examples in the manual. Commented Jun 8, 2015 at 11:55
  • what if I wanna chan ge the order, from bigger to lees, what can I change in ur function for make it work, thansk? Commented Oct 22, 2016 at 12:30

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.