Reputation: 9838
I have an array of objects which have a property id
I wish to sort by. This property contains the numbers as strings. I am trying to cast these strings to ints to sort them.
array(
object(stdClass)#10717 (26) {
["id"]=>
string(2) "12"
},
object(stdClass)#10718 (26) {
["id"]=>
string(2) "13"
}
object(stdClass)#10719 (26) {
["id"]=>
string(2) "8"
}
...
My code is as such
class Test
{
public static function test( $array ) {
usort( $array, 'callBackSort')
return $array;
}
function callBackSort( $a, $b ) {
$a = $a->id;
$a = (int)$a;
$b = $b->id;
$b = (int)$b;
if ( $a == $b ) {
return 0;
}
return ( $a < $b ) ? -1 : 1;
}
}
// In another file
$array = Test::test($array);
var_dump( $array );
However this is not working, the array is not sorted (no different from the original array). I am completely unfamiliar with usort.
EDIT: If I remove the callback function from the class and put it in the same file as $array = Test::test($array);
Then it seems to work.
Upvotes: 0
Views: 216
Reputation: 1154
I believe the problem is that your usort() function is trying to call a non-static method called "callBackSort" from within a static context.
To keep your callBackSort function in the same file (class) as the "test" method, make it static and either public, protected or private depending on whether you will have use for it elsewhere, and call it by passing an array as the second argument to usort.
By the by, your callBackSort function is a little more complex than it needs to be. You don't need to cast the values to int to do comparisons.
class Test
{
public static function test( $array ) {
//this will call a static method called "callBackSort" from class "Test" - equivalent to calling Test::callBackSort()
usort( $array, array("Test", "callBackSort"));
return $array;
}
public static function callBackSort( $a, $b ) {
if ( $a->id == $b->id ) {
return 0;
}
return ( $a->id < $b->id ) ? -1 : 1;
}
}
See this answer for a similar case: Using usort in php with a class private function
Upvotes: 1