如果这是一个有点奇怪的问题,我很抱歉。我正在尝试确定每个对象(分配有两个变量 [rounds, x])。
回合表示物体在赛道上移动了多少次(比如赛车?x 是对象从开始开始的距离(其中目标是 750)。当物体达到 750 或更高时,位置将重置并在其回合中添加 +1。
我需要确定每个对象的位置/等级。就像我们有这个:
array("id"=>"object1", "rounds"=>5, "x"=>520)
array("id"=>"object2", "rounds"=>10, "x"=>140)
array("id"=>"object3", "rounds"=>10, "x"=>10)
以下是排名:1. 对象 22. 对象 33. 对象 1
您认为如何做到这一点的最佳方法?我已经尝试了我现在能想出的任何想法,但我无法在不出错或不存在对象的情况下弄清楚这一点。
谢谢!
据我了解,您需要以自定义方式对二维数组进行排序。
试试这个代码:
$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);
几乎可以肯定有更好(更有效)的方法,但这应该有效:
$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;
也许是这样的事情?
$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);