Skip to content
Advertisement

Sort array by numbers, when the same numbers, sort by alphabet

I am trying to solve problem with sorting. As I´ve written to the title, I need to sort array by numbers, but when some rows have the same number, sort them by alphabet. I was trying to make this with two sorts, but when I use sort by numbers and than second one by alphabet, it doesn’t work.. So I’ve tried to change the order of functions, but still, after number sorting, it doesn’t keep alphabetical sort at all… Could someone tell me what to edit please?

Code below:

        $nodesToSort = $this->openedContextMenu->getPreparedNodes();

        $labelSort = function($x, $y)
        {
            $xTranslated = $this->getPresenter()->translator->translate($x->label);
            $yTranslated = $this->getPresenter()->translator->translate($y->label);
            return strcmp($xTranslated, $yTranslated);
        };

        $compareSort = function ($a, $b)
        {
            if ($a->sort == $b->sort) {
                return 0;
            }
            return ($a->sort < $b->sort) ? -1 : 1;
        };

        usort($nodesToSort, $labelSort);
        usort($nodesToSort, $compareSort);

Advertisement

Answer

SOLVED. I just had to merge that two functions.

    $compareSort = function ($a, $b)
    {
        if ($a->sort == $b->sort) {
            $xTranslated = $this->getPresenter()->translator->translate($a->label);
            $yTranslated = $this->getPresenter()->translator->translate($b->label);
            return strcasecmp($xTranslated, $yTranslated);
        }
        return ($a->sort < $b->sort) ? -1 : 1;
    };
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement