如果这是一个有点奇怪的问题,我很抱歉。我正在尝试确定每个对象(分配两个变量[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.对象2 2.对象3 3.对象1
您认为最好的方法是什么?我已经尝试过任何想法,我现在可以想出来,但我无法弄清楚这一点,而不会出现错误或不存在的对象。
谢谢!
答案 0 :(得分:2)
据我了解,您需要以自定义方式对二维数组进行排序。
试试这段代码:
$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);
答案 1 :(得分:0)
几乎可以肯定有一种更好(更有效)的方式,但这应该有效:
$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;
答案 2 :(得分:0)
这样的事可能吗?
$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);