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!

有帮助吗?

解决方案

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);

其他提示

There's almost certainly a better (more efficient) way, but this should work:

$places = Array(
    array("id"=>"object1", "rounds"=>5, "x"=>520),
    array("id"=>"object2", "rounds"=>10, "x"=>140),
    array("id"=>"object3", "rounds"=>10, "x"=>10)
);

$placesGroupedByRealX = Array();

foreach( $places as $place ) {
    /**
     * rounds = 750x
     */
    $realX = ((int)$place['rounds'] x 750) + $place['x'];

    /**
     * Make each $placesGroupedByRealX an array for the value of 
     * $place["rounds"] if it isn't already.
     */
    $placesGroupedByRealX[ $realX ] = ( isset($placesGroupedByRealX[ $realX ]))
        ? $placesGroupedByRealX[ $realX ]
        : Array();

    // We store into the array to prevent over-writes, even though 
    // it feels clunky
    $placesGroupedByRealX[ $realX ][] = $place;
}

/**
 * Order them by realX descending
 */
natsort($placesGroupedByRealX);
$placesGroupedByRealX = array_reverse($placesGroupedByRealX, true);

$results = Array();

/**
 * Iterate over the nested arrays and add them a resultset
 */
foreach ( $placesGroupedByRealX as $score => $place ) {
    $results[] = $place;
}

//results should now be your places ordered highest to lowest for x and rounds.
$results;    

Something like this maybe?

$contestants; = array();
array_push($array1);
array_push($array2);
array_push($array2);

$places = array();

foreach ($contestants as $index => $contestant) {
    $distance = ($contestant['rounds'] * 750) + $contestant['x'];
    $places[$distance] = $contestant['id'];
};

$result = rsort($places);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top