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

克里斯·琼斯

我有一个看起来像这样的数组:

[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中执行此操作?

Pablo Digiani

您可以使用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");

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章