brietsparks
brietsparks

Reputation: 5006

sort array of objects by variable obj property

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?

Upvotes: 3

Views: 192

Answers (3)

WHY
WHY

Reputation: 278

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 =============
// ===============================================

Upvotes: 0

FuzzyTree
FuzzyTree

Reputation: 32392

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'

Upvotes: 3

Ray
Ray

Reputation: 41408

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.

Upvotes: 1

Related Questions