Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP usort array with custom attribute

How to sort an array of objects by

$object->get_attribute($var)

where $var is input from function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I do this?

usort with cmp function doesn’t allow variables, does it?

>Solution :

You can sort an array of objects by a specific attribute using the usort function and a custom comparison function. You can pass the variable $var as a parameter to the comparison function.

function sortObjectsByAttribute($array, $var) {
    usort($array, function($a, $b) use ($var) {
        return $a->get_attribute($var) - $b->get_attribute($var);
    });
    return $array;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading