Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort array of objects by variable obj property

Tags:

php

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?

like image 756
brietsparks Avatar asked Dec 12 '25 10:12

brietsparks


1 Answers

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'

like image 127
FuzzyTree Avatar answered Dec 14 '25 01:12

FuzzyTree



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!