2

我目前正在开发一个使用 JSON 转换为关联多维数组的项目,并且遇到了一些问题。我的数组如下所示:

Array
(
    [IS-4] => Array
    (
        [0] => Array
            (
                [player] => Bulgerian_Soldier
                [dmg] => 241138
                [battles] => 113
                [avg_dmg] => 2134
            )

        [1] => Array
            (
                [player] => Lt_Towerladder
                [dmg] => 106841
                [battles] => 52
                [avg_dmg] => 2055
            )

        [2] => Array
            (
                [player] => Timroden
                [dmg] => 1090983
                [battles] => 686
                [avg_dmg] => 1590
            )

        [3] => Array
            (
                [player] => wunahokalugi
                [dmg] => 235883
                [battles] => 129
                [avg_dmg] => 1829
            )

        [clan_avg_dmg] => 1709
    )...

我想做的是对 by 内IS-4的所有数组进行排序avg_dmg,但没有任何成功。我正在使用以下内容对所有数据进行排序。

$tanks_dd = array();

foreach($tanks as $tankname => $tank) {
$tanks_dd[$tankname] = array(); 


$dmg_max = 0;   
$total_dmg = 0;
$battles = 0;

for($i=0; $i < count($tank); $i++) {        
    $player = $tanks[$tankname][$i];

    if($player['avg_dmg'] > $dmg_max) {
        $dmg_max = $player['avg_dmg'];
        array_unshift($tanks_dd[$tankname], $tanks[$tankname][$i]);
    } else {
        array_push($tanks_dd[$tankname], $tanks[$tankname][$i]);    
    }
    $total_dmg = $total_dmg + $player['dmg'];
    $battles = $battles + $player['battles'];
}
$tanks_dd[$tankname]['clan_avg_dmg'] = $battles == 0 ? 0 : round($total_dmg / $battles);
}
4

1 回答 1

3

你会想要使用 php 的 usort:

http://www.php.net/manual/en/function.usort.php

由于您只想按 'avg_dmg' 对 $tanks_dd['IS-4'] 的内容进行排序,因此应该使用以下代码:

usort($tanks_dd['IS-4'],function($a,$b){
    return $a['avg_dmg']>$b['avg_dmg'];
});
//$tanks_dd['IS-4'] is now sorted by avg_dmg
于 2013-05-02T04:37:29.210 回答