3

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?

Community
  • 1
  • 1
brietsparks
  • 4,776
  • 8
  • 35
  • 69
  • Example #4 in the [usort documentation](http://us3.php.net/manual/en/function.usort.php) appears to do something along those lines. – Patrick Q Jun 30 '14 at 20:04

3 Answers3

3

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'

Community
  • 1
  • 1
FuzzyTree
  • 32,014
  • 3
  • 54
  • 85
1

You could add a static property to the class $a & $b belong to or a shared parent class. You can call it something like 'sort_property', and then use that:

   //Set the sort property 
   Class_of_a_and_b::$sort_property = 'name';

   //call sort
   usort($array_of_obj, "cmp");

   //....stuff ...

   function cmp($a, $b)
   {
         //in real code, maybe test if the sort property is valid...
         $sort_prop = Class_of_a_and_b::$sort_property;
         return strcmp($a->$sort_prop , $b->$sort_prop );
   }

Of course this only works well if they're objects of the same class.

Ray
  • 40,256
  • 21
  • 101
  • 138
0

Just an idea

// ===============================================
// Start => Sort Object / Array by Key ===========
// ===============================================
function usort_array($array, $key, $order = 'asc') {
    if(strtolower($order) == 'asc')
        usort($array, function($a, $b) use ($key) { return strcmp($a[$key], $b[$key]); });
    else
        usort($array, function($a, $b) use ($key) { return strcmp($b[$key], $a[$key]); });
    return $array;
}

function usort_object($object, $key, $order = 'asc') {
    if(strtolower($order) == 'asc')
        usort($object, function($a, $b) use ($key) { return strcmp($a->$key, $b->$key); });
    else
        usort($object, function($a, $b) use ($key) { return strcmp($b->$key, $a->$key); });
    return $object;
}
// ===============================================
// End => Sort Object / Array by Key =============
// ===============================================
WHY
  • 258
  • 1
  • 8