I am sorting an array of objects by object property using this process:
function cmp($a, $b)
{
return strcmp($a->name, $b->name);
}
usort($array_of_obj, "cmp"); //sorts array by object name
In my case, the object property is stored as in variable $prop, so that I can choose which property to sort from (name, date, etc). So, I would like something like this:
function cmp($a, $b, $prop)
{
return strcmp($a->$prop, $b->$prop);
}
$prop = 'someproperty';
usort($array_of_obj, "cmp"); //sorts array by chosen object property, $prop
My problem here is that I cannot pass a value to the $prop argument when I call the "cmp" function. I'm not sure if I should if this is a dead end endeavor or if there is some way to work around this. What can I do?
You could wrap the call inside an anonymous function
function cmp($a, $b, $prop) {
return strcmp($a->$prop, $b->$prop);
}
$prop = 'someproperty';
usort($array_of_obj, function($a,$b) use ($prop) {
return cmp($a,$b,$prop);
});
EDIT: Explanation of the keyword 'use'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With