laminatefish
laminatefish

Reputation: 5246

Sorting array of objects to list top 5 and bottom 5 elements based on object value

having some issues getting the following code to act as I need. I'm attempting to display the top 5 and bottom 5 scores. I thought the below code would work, but the sorting seems quite random. I'd expect the top 5 to sort as: 80, 50, 30, 12, 1 and the bottom 5 to display as -1, -12, -30, -50, -80. Are there any other (possibly, more preferred ways) of doing this?

        // Check for excessive number of locations and supply top 5 and bottom 5
        if (count($this->viewData->locations) > 10) {
            usort($this->viewData->locations, function($firstVal, $nextVal) {
                return ($firstVal->nps > $nextVal->nps);
            });

            $top5Locations = array_slice($this->viewData->locations, 0, 5);
            usort($this->viewData->locations, function($firstVal, $nextVal) {
                return ($firstVal->nps < $nextVal->nps);
            });

            $bottom5Locations = array_slice($this->viewData->locations, 0, 5);
            $this->viewData->locations = null;
            $this->viewData->locations = array_merge($top5Locations, $bottom5Locations);
        }

Cheers

Upvotes: 1

Views: 58

Answers (1)

Ollie in PGH
Ollie in PGH

Reputation: 2629

Have you tried just skipping the second usort and getting the bottom five by array slicing from the end of the array?

       // Check for excessive number of locations and supply top 5 and bottom 5
    if (count($this->viewData->locations) > 10) {
        usort($this->viewData->locations, function($firstVal, $nextVal) {

            return ($firstVal->nps > $nextVal->nps);
        });

        $top5Locations = array_slice($this->viewData->locations, 0, 5);
        $bottom5Locations = array_slice($this->viewData->locations, -5, 5);
        $this->viewData->locations = null;
        $this->viewData->locations = array_merge($top5Locations, $bottom5Locations);
    }

Here's how to array slice from the end: http://php.net/manual/en/function.array-slice.php

Upvotes: 1

Related Questions