通过添加几个字段在php中对多维数组进行排序

时间:2015-11-13 13:52:29

标签: php arrays sorting multidimensional-array

我有一个如下所示的数组:

[0] => Array
(
    [ID] => 1
    [total_1] => 200
    [total_2] => 10
    [total_3] => 420
    [name] => testname1
)

[1] => Array
(
    [ID] => 2
    [total_1] => 900
    [total_2] => 30
    [total_3] => 40
    [name] => testname1
)

[2] => Array
(
    [ID] => 3
    [total_1] => 900
    [total_2] => 40
    [total_3] => 90
    [name] => testname1
)

我需要按total_1,total_2和total_3的总和对其进行排序。因此,在此示例中,如果我以正确的降序排序顺序输出ID键,则为:

3,2,1

任何人都可以告诉我如何在PHP中执行此操作?

1 个答案:

答案 0 :(得分:1)

您可以使用usort函数并比较值的总和:

function cmp($arr1, $arr2){
    $sum1 = $arr1['total_1'] + $arr1['total_2'] + $arr1['total_3']; 
    $sum2 = $arr2['total_1'] + $arr2['total_2'] + $arr2['total_3'];
    if ($sum1 == $sum2) {
       return 0;
    }
    return ($sum1 < $sum2) ? -1 : 1;
}

usort($array, "cmp");