【问题标题】:Rank system - Determine ranking of multiply objects assigned with two variables排名系统 - 确定分配有两个变量的乘法对象的排名
【发布时间】:2014-02-10 18:44:59
【问题描述】:

如果这是一个有点奇怪的问题,我很抱歉。我正在尝试确定每个对象(分配有两个变量 [rounds, x])。

Rounds 表示物体在轨道上移动了多少次(比如赛车?) 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

您认为最好的方法是什么?我已经尝试了我现在能想到的任何想法,但我无法在没有错误或不存在对象的情况下解决这个问题。

谢谢!

【问题讨论】:

  • 换句话说,您要对此类数组(对象)的数组进行排序?

标签: php arrays ranking


【解决方案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);

【讨论】:

  • 有些功能我忘记了。很好的解决方案!
  • 这可能行得通——我最后的想法是将它放在一个字符串 XX-XX-XX 中并对其进行排序——但话又说回来,这意味着我必须切换某些值的含义。 . 谢谢!!
【解决方案2】:

几乎可以肯定有一种更好(更有效)的方法,但这应该可行:

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

【讨论】:

    【解决方案3】:

    可能是这样的吗?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 2018-03-20
      • 2012-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多