Ranking (with duplicates) of collection/array in php (Laravel)

  collections, foreach, laravel, php

I built a collection with Laravel which outputs json. It’s supposed to be a ranking with name, score and rank attributes. The scores are already sorted and they need their correct ranking. When 2 or more scores are the same, they should have the same ranking number and the one that comes next should have the next number.

Example:
Nick – 28 pts – 1
Sarah – 25 pts – 2
Bret – 22 pts – 3
Sofie – 22pts – 3
Justin – 20pts – 4
etc

At the moment I have this result:

{
    "data": [
        {
            "rank": 1,
            "name": "Jari",
            "score": 51
        },
        {
            "rank": 2,
            "name": "Kenny",
            "score": 50
        },
        {
            "rank": 2,
            "name": "Lisa",
            "score": 50
        },
        {
            "rank": 4,
            "name": "Sven",
            "score": 44
        },
        {
            "rank": 5,
            "name": "Laurens",
            "score": 37
        },
        {
            "rank": 6,
            "name": "Maxim",
            "score": 35
        },
        {
            "rank": 6,
            "name": "Kevin",
            "score": 35
        },
        {
            "rank": 6,
            "name": "Joachim",
            "score": 35
        },
        {
            "rank": 9,
            "name": "Geoffrey",
            "score": 19
        },
        {
            "rank": 10,
            "name": "Elke",
            "score": 8
        }
    ]
}

This is the function in my controller:

  public function addRanks()
    {
        $scores = $this->makeCollection();
        $duplicateScores = $this->makeCollection();

        foreach ($scores as $key => $score) {
            foreach ($duplicateScores as $duplicateKey => $duplicateScore) {
                if ($score['score'] == $duplicateScore['score']) {
                    $score['rank'] = $key = $duplicateKey;
                    break;
                }
            }
            $score['rank'] = $key + 1;
        }
        return $scores;
    }

The $key variable should be stopping with counting, as I would expect, but it sadly doesn’t. Does this code make sense or am I looking at this wrong?

Source: Ask PHP

LEAVE A COMMENT