Search code examples
phparraysranking

Rank system - Determine ranking of multiply objects assigned with two variables


I'm sorry if this is a little strange question. I'm trying to determine every object (assigned with two variables [rounds, x]).

Rounds means how many time the object have moved around a track (like a race car?) x is how far the object is form start (where goal is 750). When the object hits 750 or above the position will reset and add a +1 to its rounds.

I need to determine the placement/rank of every object. Like if we have this:

array("id"=>"object1", "rounds"=>5, "x"=>520)

array("id"=>"object2", "rounds"=>10, "x"=>140)

array("id"=>"object3", "rounds"=>10, "x"=>10)

Here is the ranking: 1. Object 2 2. Object 3 3. Object 1

How do you think is the best way to do this? I have tried any idea i can come up with right now, but i cant figure this out without getting wrong or non existence objects.

Thanks!


Solution

  • As far as I understood you need to sort 2-dimensional array in a custom way.

    Try this code:

    $array = array(
        array('id'=>'object1', 'rounds'=>5, 'x'=>520),
        array('id'=>'object2', 'rounds'=>10, 'x'=>140),
        array('id'=>'object3', 'rounds'=>10, 'x'=>10),
    );
    usort($array, function ($a, $b) {
        $a['rounds'] * 750 + $a['x'] < $b['rounds'] * 750 + $b['x'];
    });
    print_r($array);