Home > Back-end >  Why usort does not sort?
Why usort does not sort?

Time:04-15

Code is:

private function sortCategories($categories)
{

     usort($categories, function ($first, $second) {
        return (int) $first->category_order < (int)$second->category_order  ? -1 : 1;
    });
}

Dump data is:

array(8) {
  [0]=>
  object(stdClass)#138 (23) {
    string(0) ""
    ["category_order"]=>
    string(1) "8"
     }
  }

Using sorting is:

this->sortCategories($data["categories"]);
var_dump($data["categories"]); // Here I see unsored data

So as result I need to get sorted array

CodePudding user response:

You'll have to pass the array in as a reference if you want it to be modified (and not overwrite it by a return value from the method):

private function sortCategories(&$categories)
{
 // ...
}

(Note the added &)

CodePudding user response:

Tacking onto ArSeN's answer, a proper comparator also needs to return zero when the inputs are equivalent, otherwise you're likely to get some funky sorting.

You can accomplish this with:

return (int)$first->category_order - (int)$second->category_order;

or use the "Spaceship Operator":

return (int)$first->category_order <=> (int)$second->category_order;
  •  Tags:  
  • php
  • Related