To be honest i have two problems here, one im new to Yii framework and the usort functions i have found on the net do not make sense to me. I havent found one that explains in laymans terms what is going on.
In short i have an object array something like this:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Mary Jane
[count] => 420
)
[1] => stdClass Object
(
[id] => 4
[name] => Johnny
[count] => 234
)
[2] => stdClass Object
(
[id] => 3
[name] => Kathy
[count] => 4354
)
.... I want to sort the object by id The problem is the data is sorted by date it was last updated rather than ID and i need to know the last ID because what i do is pull the data from the API into my database so im essentially checking to see the last API id is 1100 but my database last id is 1050 so i know im approx 50 records behind.
So i have created a public static function in the activity Model
public static function sort_api_data_by_id($a, $b)
{
return strcmp($a->id, $b->id);
}
And in one of my pages i am running the usort functions
usort($array, Activity::model()->sort_api_data_by_id());
If it makes a difference, the file is a view under activity so its accessing the function in the activity model so its not a different model/view relationship or anything.
I got that function from another page but what i don't understand is what i need to pass to the function for parameters $a and $b, in none of the examples does it seem to pass anything. sort_api_data_by_id is the function in the activity model.
Now may while it might be more efficient to just find the highest id rather than sort the whole object i still need to process the data later and enter it into the database and thats going to be easier if its in a logical order.
I eventually found the solution hidden within google.
I put this static function in the Activity Model:
public static function sort_api_data_by_id($a, $b){
if ($a->id == $b->id) return 0;
return ($a->id < $b->id) ? -1 : 1;
}
And then i call it with ClassName::function_name but you drop the ($a,$b). Thats what initially threw me was it didnt make sense there were parameters in the function but we werent passing any but i believe we are passing them in a roundabout way through usort and $a is the array and $b is the result of the function i.e is the id higher or lower although i could be wrong as its a bit difficult to get your head around so please take this as my understanding and not fact. I have not really seen it explained full anywhere else.
In any case this usort function then works by passing it the array and the static function
usort($array, "Activity::sort_api_data_by_id");