Reputation: 57
I have array of json objects and I want to sort it ascending and also put the null values in the end. following is the code I tried. Both uasort() is working perfectly fine individually but When I put them one after another, it just sort the array based on the latest function.
How can I sort the array in ascending order and also put null values at the end of that ascending sorted list?
uasort($arr, function($a,$b) {
return $a->score > $b->score ? 1 : -1;
});
uasort($arr, function($a) {
return ( is_null($a->score==NULL) OR $a->score == "") ? 1 : -1;
});
Upvotes: 1
Views: 521
Reputation: 781761
Use one comparison function that tests both conditions.
uasort($arr, function($a, $b) {
if ($a->score === $b->score) {
return 0;
}
if ($a->score === NULL || $a->score === "") {
return 1;
}
if ($b->score === NULL || $b->score === "") {
return -1;
}
return $a->score > $b->score ? 1 : -1;
}
Upvotes: 2